Downloads:

33

Downloads of v 0.1.0:

33

Last Update:

23 Sep 2020

Package Maintainer(s):

Software Author(s):

  • Baptiste Cabrera

Tags:

dac dacpac sqlproj dacpackage sqlproject Windows Linux MacOS

Bca.Dac

0.1.0 | Updated: 23 Sep 2020

Downloads:

33

Downloads of v 0.1.0:

33

Maintainer(s):

Software Author(s):

  • Baptiste Cabrera

Bca.Dac 0.1.0

All Checks are Passing

2 Passing Test


Validation Testing Passed


Verification Testing Passed

Details

To install Bca.Dac, run the following command from the command line or from PowerShell:

>

To upgrade Bca.Dac, run the following command from the command line or from PowerShell:

>

To uninstall Bca.Dac, run the following command from the command line or from PowerShell:

>

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

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

  • 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://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. Enter your internal repository url

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

4. Choose your deployment method:


choco upgrade bca-dac -y --source="'STEP 3 URL'" [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 bca-dac -y --source="'STEP 3 URL'"
$exitCode = $LASTEXITCODE

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

Exit $exitCode

- name: Ensure bca-dac installed
  win_chocolatey:
    name: bca-dac
    state: present
    version: 0.1.0
    source: STEP 3 URL

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

Coming early 2020! Central Managment Reporting available now! More information...


chocolatey_package 'bca-dac' do
  action    :install
  version  '0.1.0'
  source   'STEP 3 URL'
end

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


Chocolatey::Ensure-Package
(
    Name: bca-dac,
    Version: 0.1.0,
    Source: STEP 3 URL
);

Requires Otter Chocolatey Extension. See docs at https://inedo.com/den/otter/chocolatey.


cChocoPackageInstaller bca-dac
{
   Name     = 'bca-dac'
   Ensure   = 'Present'
   Version  = '0.1.0'
   Source   = 'STEP 3 URL'
}

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


package { 'bca-dac':
  provider => 'chocolatey',
  ensure   => '0.1.0',
  source   => 'STEP 3 URL',
}

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


salt '*' chocolatey.install bca-dac version="0.1.0" source="STEP 3 URL"

See docs at https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.chocolatey.html.

5. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

This package was approved by moderator flcdrg on 25 Sep 2020.

Description

PowerShell Module to manage DAC packages and SQL Projects.


tools\Bca.Dac\Bca.Dac.psd1
#
# Module manifest for module 'Bca.Dac'
#
# Generated by: Baptiste Cabrera
#
# Generated on: 9/23/2020
#

@{

# Script module or binary module file associated with this manifest.
RootModule = 'Bca.Dac'

# Version number of this module.
ModuleVersion = '0.1.0'

# Supported PSEditions
# CompatiblePSEditions = @()

# ID used to uniquely identify this module
GUID = '0f45d6b0-d4d2-467c-8fe0-ae524f814f5c'

# Author of this module
Author = 'Baptiste Cabrera'

# Company or vendor of this module
CompanyName = 'Bca'

# Copyright statement for this module
Copyright = '(c) 2020 Bca. All rights reserved.'

# Description of the functionality provided by this module
Description = 'PowerShell Module to manage DAC packages and SQL Projects.'

# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.1'

# 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 Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''

# Processor architecture (None, X86, Amd64) 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 (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Get-DacDllPath', 'Publish-DacPac', 'Set-DacDllPath', 
               'Set-SqlProjectVersion', 'Unpublish-DacPac'

# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()

# Variables to export from this module
# VariablesToExport = @()

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

    #projectSourceUrl of this module
    projectSourceUrl = 'https://github.com/baptistecabrera/bca-dac/tree/master/src'

    #docsUrl of this module
    docsUrl = 'https://github.com/baptistecabrera/bca-dac/tree/master/doc'

    #repositoryUrl of this module
    repositoryUrl = 'https://github.com/baptistecabrera/bca-dac.git'

    #License of this module
    License = 'MIT'

    #packageSourceUrl of this module
    packageSourceUrl = 'https://github.com/baptistecabrera/bca-dac/tree/master/src'

    #bugTrackerUrl of this module
    bugTrackerUrl = 'https://github.com/baptistecabrera/bca-dac/issues'

    #mailingListUrl of this module
    mailingListUrl = 'https://github.com/baptistecabrera/bca-dac/issues'

    PSData = @{

        # Tags applied to this module. These help with module discovery in online galleries.
        Tags = 'dac','dacpac','sqlproj','dacpackage','sqlproject','Windows','Linux','MacOS'

        # A URL to the license for this module.
        LicenseUri = 'https://github.com/baptistecabrera/bca-dac/blob/master/LICENSE'

        # A URL to the main website for this project.
        ProjectUri = 'https://github.com/baptistecabrera/bca-dac'

        # A URL to an icon representing this module.
        IconUri = 'https://www.powershellgallery.com/Content/Images/Branding/packageDefaultIcon.png'

        # ReleaseNotes of this module
        ReleaseNotes = '0.1.0:
- Publish-DacPac / Unpublish-DacPac: functions to deploy or undeploy a DAC packages;
- Get-DacDllPath/Set-DacDllPath: functions to get or set the path to the DAC DLL used to deploy or undeploy;
- Set-SqlProjectVersion: function to set the version in a SQL Project file;
- Supports Windows, Linux and MacOS;
- Supports English and French language.'

        # Prerelease string of this module
        # Prerelease = ''

        # Flag to indicate whether the module requires explicit user acceptance for install/update/save
        # RequireLicenseAcceptance = $false

        # External dependent modules of this module
        # ExternalModuleDependencies = @()

    } # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}

tools\Bca.Dac\Bca.Dac.psm1
try
{
    # Importing Localized Data if present (fallback to en-US)
    if (Test-Path (Join-Path $PSScriptRoot LocalizedData))
    {
        $script:LocalizedData = Import-LocalizedData -BaseDirectory (Join-Path $PSScriptRoot LocalizedData) -ErrorAction SilentlyContinue
        if (!$?) { $script:LocalizedData = Import-LocalizedData -UICulture en-US -BaseDirectory (Join-Path $PSScriptRoot LocalizedData) }
    }

    # Gets public and private function definition files.
    $Public = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -Recurse -ErrorAction SilentlyContinue )
    $Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -Recurse -ErrorAction SilentlyContinue )

    # Dot source the files
    foreach ($File in @($Public + $Private))
    {
        try
        {
            . $File.FullName
        }
        catch
        {
            Write-Error -Message ($script:LocalizedData.ImportModule.Error.ImportError.Message -f $File.BaseName, $_) -Category OperationStopped -CategoryActivity $MyInvocation.MyCommand -TargetName $File.BaseName -TargetType $script:LocalizedData.ImportModule.Error.ImportError.Target -Exception OperationStoppedException
        }
    }

    # Exports public functions and their aliases
    Export-ModuleMember -Function $Public.BaseName -Alias *
}
catch 
{
    Write-Error $_
}
tools\Bca.Dac\Bca.Dac.Tests.ps1
if (Test-Path (Join-Path $PSScriptRoot LocalizedData))
{
    $global:TestLocalizedData = Import-LocalizedData -BaseDirectory (Join-Path $PSScriptRoot LocalizedData) -ErrorAction SilentlyContinue
    if (!$?) { $global:TestLocalizedData = Import-LocalizedData -UICulture en-US -BaseDirectory (Join-Path $PSScriptRoot LocalizedData) }
}

Describe $global:TestLocalizedData.Module.Describe {
    BeforeAll {
        $ParentDirectory = Split-Path $PSScriptRoot -Parent
        $Directory = Split-Path $PSScriptRoot -Leaf

        if ([version]::TryParse($Directory, [ref]$null)) { $ModuleName = Split-Path $ParentDirectory -Leaf }
        else { $ModuleName = $Directory }
    }

    It $global:TestLocalizedData.Module.ImportModule {
        try
        {
            Import-Module (Join-Path $PSScriptRoot ("{0}.psd1" -f $ModuleName)) -Force
            $Result = $true
        }
        catch { $Result = $false }
        $Result | Should -Be $true
    }
    
    It $global:TestLocalizedData.Module.CommandCheck {
        $Commands = Get-Command -Module $ModuleName
        $Commands.Count | Should -BeGreaterThan 0
    }
}

Describe $global:TestLocalizedData.DllPath.Describe {
    BeforeAll {
        $SqlServerModule = $SqlServerModule = Get-Module SqlServer -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
        if (!$SqlServerModule)
        {
            Find-Module SqlServer | Install-Module -Scope CurrentUser -Force
            $SqlServerModule = $SqlServerModule = Get-Module SqlServer -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
        }
        $DacDllPath = Join-Path $SqlServerModule.ModuleBase "Microsoft.SqlServer.Dac.dll"
        $NotDacDllPath = Join-Path ([System.IO.Path]::GetTempPath()) "Microsoft.SqlServer.Dac.notdll"
    }

    It $global:TestLocalizedData.DllPath.GetDllModule {
        try
        {
            $DllPath = Get-DacDllPath
            $Result = $true
        }
        catch { $Result = $false }
        $Result | Should -Be $true
        $DllPath | Should -BeExactly $DacDllPath
    }
    
    It $global:TestLocalizedData.DllPath.SetDllFullPath {
        try
        {
            Set-DacDllPath -Path $DacDllPath
            $DllPath = Get-DacDllPath
            $Result = $true
        }
        catch { $Result = $false }
        $Result | Should -Be $true
        $DllPath | Should -BeExactly $DacDllPath
    }

    It $global:TestLocalizedData.DllPath.SetDllFullPath {
        try
        {
            Set-DacDllPath -Path (Join-Path ([System.IO.Path]::GetTempPath()) "Microsoft.SqlServer.Dac.dll") -ErrorAction Stop
            $DllPath = Get-DacDllPath
            $Result = $true
        }
        catch
        {
            $DllPath = Get-DacDllPath
            $Result = $false
        }
        $Result | Should -Be $false
        $DllPath | Should -BeExactly $DacDllPath
    }

    It $global:TestLocalizedData.DllPath.SetDllFullPath {
        try
        {
            New-Item -Path $NotDacDllPath -ItemType File -Force | Out-Null
            Set-DacDllPath -Path $NotDacDllPath -ErrorAction Stop
            $DllPath = Get-DacDllPath
            $Result = $true
        }
        catch
        {
            $DllPath = Get-DacDllPath
            $Result = $false
        }
        $Result | Should -Be $false
        $DllPath | Should -BeExactly $DacDllPath
    }

    It $global:TestLocalizedData.DllPath.SetDllDirectory {
        try
        {
            Set-DacDllPath -Path (Split-Path $DacDllPath -Parent)
            $DllPath = Get-DacDllPath
            $Result = $true
        }
        catch { $Result = $false }
        $Result | Should -Be $true
        $DllPath | Should -BeExactly $DacDllPath
    }

    It $global:TestLocalizedData.DllPath.SetDllDirectory {
        try
        {
            Set-DacDllPath -Path ([System.IO.Path]::GetTempPath()) -ErrorAction Stop
            $DllPath = Get-DacDllPath
            $Result = $true
        }
        catch
        {
            $DllPath = Get-DacDllPath
            $Result = $false
        }
        $Result | Should -Be $false
        $DllPath | Should -BeExactly $DacDllPath
    }
}
tools\Bca.Dac\LocalizedData\en\Bca.Dac.psd1
@{
    Global                 = @{
        Debug = @{
            Entering = "Entering '{0}'"
            Leaving  = "Leaving '{0}'"
        }
    }

    ImportModule           = @{
        Error = @{
            ImportError = @{
                Message = "Failed to import function '{0}': {1}"
                Target  = "Function"
            }
        }
    }

    GetDacDllPath          = @{
        Verbose = @{
            FromModule = "Looking for module 'SqlServer'."
        }
    }

    PublishUnpublishDacPac = @{
        Verbose = @{
            LoadDll       = "Loading Dac DLL from '{0}'."
            LoadProfile   = "Loading Dac profile from '{0}'."
            DeployOption  = "Setting deployment option '{0}' to '{1}'."
            LoadService   = "Loading Dac service to '{0}'."
            LoadPackage   = "Loading Dac package from '{0}'."
            TestDb        = "Testing if database '{0}' already exists."
            DriftReport   = "Creating drift report."
            NoDriftReport = "Not creating drift report, either option was not specified or database '{0}' does not exist yet." 
            KillSessions  = "Terminating sessions to database '{0}'."
            DeployReport  = "Creating deployment report."
            DeployScript  = "Creating deployment script."
            DeployDacPac  = "Deploying database package '{0}'."
            UnregisterDac = "Unregistering package '{0}' with mode '{1}'."
            ReportPath    = "Deployment reports and scripts, if any, can be found under '{0}'."
        }

        Warning = @{
            CantKillSessions = "Could not kill sessions to database '{0}'."
            DbDoesntExist    = "Database '{0}' does not exist yet."
        }
    }

    SetDacDllPath          = @{
        Verbose = @{
            FromDirectory = "Looking for DLL in directory '{0}'."
        }

        Error   = @{
            NotFound = @{
                Message = "The DLL was not found in directory '{0}'."
                Target  = "DacDll"
            }
            NotValid = @{
                Message = "The file '{0}' is not a valid DLL file."
                Target  = "DacDll"
            }
        }
    }

    SetSqlProjectVersion   = @{
        Verbose = @{
            Directory      = "Getting .sqlproj files in folder '{0}' (Recurse: {1})."
            File           = "Adding .sqlproj file '{0}'."
            ProcessFile    = "Processing file '{0}'."
            ROFlag         = "Removing 'ReadOnly' flag if present."
            VersionUpdated = "Version updated to {0} in file '{1}'."
        }

        Warning = @{
            NotSqlProj = "File '{0}' is not a .sqlproj file, it will be ignore."
        }
    }
}
tools\Bca.Dac\LocalizedData\en\Bca.Dac.Tests.psd1
@{
    Module  = @{
        Describe     = "Module"
        ImportModule = "Importing module locally."
        CommandCheck = "Checking exported commands count."
    }

    DllPath = @{
        Describe        = "DLL Path"
        GetDllModule    = "Getting DLL Path from Module."
        SetDllFullPath  = "Setting DLL from full path."
        SetDllDirectory = "Setting DLL from directory."
    }
}
tools\Bca.Dac\LocalizedData\fr\Bca.Dac.psd1
@{
    Global       = @{
        Debug = @{
            Entering = "Début de la fonction « {0} »"
            Leaving  = "Fin de la fonction « {0} »"
        }
    }

    ImportModule = @{
        Error = @{
            ImportError = @{
                Message = "Impossible d'importer la fonction « {0} »  : {1}"
                Target  = "Fonction"
            }
        }
    }

    GetDacDllPath          = @{
        Verbose = @{
            FromModule = "Looking for module « SqlServer »."
        }
    }

    PublishUnpublishDacPac = @{
        Verbose = @{
            LoadDll       = "Chargement de la DLL Dac depuis « {0} »."
            LoadProfile   = "Chargement du profil Dac depuis « {0} »."
            DeployOption  = "Assignation de l'option de de déploiement « {0} » à « {1} »."
            LoadService   = "Chargement du service dac vers « {0} »."
            LoadPackage   = "Chargement du paquet Dac depuis « {0} »."
            TestDb        = "Vérification de l'existence de la base de données « {0} »."
            DriftReport   = "Création du rapport de dérive."
            NoDriftReport = "Pas de création de rapport de dérive, l'option n'a pas été spécifiée ou la base de données « {0} » n'existe pas." 
            KillSessions  = "Déconnections des sessions sur la base de données « {0} »."
            DeployReport  = "Création du rapport de déploiement."
            DeployScript  = "Création du script de déploiement."
            DeployDacPac  = "Déploiement du paquet Dac « {0} »."
            UnregisterDac = "Désenregistrement du paquet Dac « {0} » avec le mode « {1} »."
            ReportPath    = "Les rapports et scripts de déploiement, si applicable, se trouvent dans « {0} »."
        }

        Warning = @{
            CantKillSessions = "Impossible de terminer les sessions sur la base de données « {0} »."
            DbDoesntExist    = "La base de données « {0} » n'existe pas."
        }
    }

    SetDacDllPath          = @{
        Verbose = @{
            FromDirectory = "Recherche de la DLL dans le répertoire « {0} »."
        }

        Error   = @{
            NotFound = @{
                Message = "La DLL n'a pas été trouvée dans le répertoire « {0} »."
                Target  = "DacDll"
            }
            NotValid = @{
                Message = "Le fichier « {0} » n'est pas un fichier DLL valide."
                Target  = "DacDll"
            }
        }
    }

    SetSqlProjectVersion   = @{
        Verbose = @{
            Directory      = "Récupération des fichiers .sqlproj dans le répertoire « {0} » (Récursif: {1})."
            File           = "Ajout du fichier .sqlproj « {0} »."
            ProcessFile    = "Traitement du fichier « {0} »."
            ROFlag         = "Suppression de l'attribut « ReadOnly » si présent."
            VersionUpdated = "Version mise à jour à {0} dans le fichier « {1} »."
        }

        Warning = @{
            NotSqlProj = "Le fichier « {0} » n'est pas un .sqlproj, il sera ignoré."
        }
    }
}
tools\Bca.Dac\LocalizedData\fr\Bca.Dac.Tests.psd1
@{
    Module = @{
        Describe     = "Module"
        ImportModule = "Importation locale du module."
        CommandCheck = "Vérification du nombre de fonctions exportées."
    }

    DllPath = @{
        Describe        = "Chemin de la DLL"
        GetDllModule    = "Récupération du chemin de la DLL depuis Module."
        SetDllFullPath  = "Assignation du chemin de la DLL depuis le chemin complet."
        SetDllDirectory = "Assignation du chemin de la DLL depuis le répertoire."
    }
}
tools\Bca.Dac\Private\_Variables.ps1
$script:DacDllPath = ""
tools\Bca.Dac\Public\Get-DacDllPath.ps1
function Get-DacDllPath
{
    <#
        .SYNOPSIS
            Gets the path of the DAC DLL.
        .DESCRIPTION
            Gets the path of the DAC DLL.
        .OUTPUTS
            System.String
            Returns a String containing the path to the DLL.
        .EXAMPLE
            Get-DacDllPath

            Description
            -----------
            This example will return a string containing the path to the DLL.
        .NOTES
            This function will either retrieve the path set by Set-DacDllPath, autodiscover the path from the path the PowerShell module SqlServer if present, or return an empty string.
        .LINK
            Set-DacDllPath
    #>
    [CmdletBinding()]
    param()

    Write-Debug ($script:LocalizedData.Global.Debug.Entering -f $PSCmdlet.MyInvocation.MyCommand)
    if (!$script:DacDllPath)
    {
        Write-Verbose $script:LocalizedData.GetDacDllPath.Verbose.FromModule
        $SqlServerModule = Get-Module SqlServer -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
        if ($SqlServerModule)
        {
            $DacDllPath = Join-Path $SqlServerModule.ModuleBase "Microsoft.SqlServer.Dac.dll"
            if (Test-Path $DacDllPath) { Set-DacDllPath -Path $DacDllPath }
        }
    }
    $script:DacDllPath

    Write-Debug ($script:LocalizedData.Global.Debug.Leaving -f $PSCmdlet.MyInvocation.MyCommand)
}
tools\Bca.Dac\Public\Publish-DacPac.ps1
function Publish-DacPac
{
    <#
        .SYNOPSIS
            Publishes a DAC package.
        .DESCRIPTION
            Publishes a DAC package.
        .PARAMETER Path
            A string containing the path to the DAC package.
        .PARAMETER DacProfilePath
            A string containing the path to the DAC profile.
        .PARAMETER DeployOptions
            A hashtable containing the deployment options to use.
        .PARAMETER GenerateDriftReport
            A switch specifying whether or not to generate a drift report.
        .PARAMETER GenerateDeployReport
            A switch specifying whether or not to generate a deployment report.
        .PARAMETER GenerateDeployScript
            A switch specifying whether or not to generate a deployment script.
        .PARAMETER OutputPath
            A string containing the path where the reports and scripts will be saved.
        .PARAMETER DacDllPath
            A string containing the path to the DAC DLL.
        .PARAMETER KillSessions
            A switch specifying whether or not to terminate active session on the database if it exists.
        .PARAMETER Force
            A switch specifying whether or not to force the execution (will implicitely enable option KillSessions).
        .EXAMPLE
            Publish-DacPac -Path C:\MyProject\MyProject.dacpac -DacProfilePath C:\MyProject\MyProject.publish.xml

            Description
            -----------
            This example will deploy MyProject.dacpac based on the publish profile MyProject.publish.xml.
        .LINK
            Unpublish-DacPac
    #>
    [CmdLetBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
    param(
        [parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path $_ } )]
        [alias("DacPacPath")]
        [string] $Path,
        [parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path $_ } )]
        [alias("PublishProfilePath")]
        [string] $DacProfilePath,
        [parameter(Mandatory = $false)]
        [hashtable] $DeployOptions,
        [parameter(Mandatory = $false)]
        [switch] $GenerateDriftReport,
        [parameter(Mandatory = $false)]
        [switch] $GenerateDeployReport,
        [parameter(Mandatory = $false)]
        [switch] $GenerateDeployScript,
        [parameter(Mandatory = $false)]
        [ValidateScript( { Test-Path $_ } )]
        [alias("OutputDirectory", "OutputDir", "OutDir")]
        [string] $OutputPath = ([System.IO.Path]::GetTempPath()),
        [parameter(Mandatory = $false)]
        [ValidateScript( { Test-Path $_ } )]
        [string] $DacDllPath = (Get-DacDllPath),
        [parameter(Mandatory = $false)]
        [switch] $KillSessions,
        [Parameter(Mandatory = $false)]
        [switch] $Force
    )

    try
    {
        Write-Debug ($script:LocalizedData.Global.Debug.Entering -f $PSCmdlet.MyInvocation.MyCommand)

        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadDll -f $DacDllPath)
        Add-Type -Path $DacDllPath

        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadProfile -f $DacProfilePath)
        $DacProfile = [Microsoft.SqlServer.Dac.DacProfile]::Load($DacProfilePath)
        $DeployOptions.Keys | ForEach-Object {
            try 
            {
                Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.DeployOption -f $_, $DeployOptions[$_])
                $DacProfile.DeployOptions.$_ = $DeployOptions[$_]
            }
            catch
            {
                Write-Error $_
            }
        }
        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadService -f $DacProfile.TargetConnectionString)
        $DacService = New-Object Microsoft.SqlServer.Dac.DacServices $DacProfile.TargetConnectionString
        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadPackage -f $Path)
        $DacPac = [Microsoft.SqlServer.Dac.DacPackage]::Load($Path)

        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.TstDb -f $DacProfile.TargetDatabaseName)
        Write-Debug $DacProfile.TargetConnectionString
        try
        {
            $DbId = Invoke-Sqlcmd -ConnectionString $DacProfile.TargetConnectionString -Query "SELECT DB_ID('$($DacProfile.TargetDatabaseName)') AS [Id]" -ErrorAction SilentlyContinue
            if ($DbId.Id -eq [DBNull]::Value) { $DbExists = $false }
            else { $DbExists = $true }
        }
        catch
        {
            $DbExists = $false
        }
        Write-Debug $DbExists
        
        if ($DbExists)
        {
            if ($GenerateDriftReport)
            {
                Write-Verbose $script:LocalizedData.PublishUnpublishDacPac.Verbose.DriftReport
                $DacService.GenerateDriftReport($DacProfile.TargetDatabaseName) | Out-File (Join-Path $OutputPath "$($DacProfile.TargetDatabaseName).DriftReport.xml")
            }
            else { Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.NoDriftReport -f $DacProfile.TargetDatabaseName) }
            if ($KillSessions)
            {
                Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.KillSessions -f $DacProfile.TargetDatabaseName)
                try { Invoke-Sqlcmd -ConnectionString $DacProfile.TargetConnectionString -Query "DECLARE @SQL nvarchar(1000); SELECT @SQL = COALESCE(@SQL,'') + 'KILL ' + Convert(varchar, session_id) + ';' FROM sys.dm_exec_sessions WHERE database_id = DB_ID('$($DacProfile.TargetDatabaseName)') AND session_id > 8 AND session_id <> @@SPID; EXEC (@SQL)" | Out-Null }
                catch { Write-Warning ($script:LocalizedData.PublishUnpublishDacPac.Warning.CantKillSessions -f $DacProfile.TargetDatabaseName) }
            }
        }
        else { Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.NoDriftReport -f $DacProfile.TargetDatabaseName) }

        if ($GenerateDeployReport)
        {
            Write-Verbose $script:LocalizedData.PublishUnpublishDacPac.Verbose.DeployReport
            $DacService.GenerateDeployReport($DacPac, $DacProfile.TargetDatabaseName, $DacProfile.DeployOptions) | Out-File (Join-Path $OutputPath "$($DacProfile.TargetDatabaseName).DeployReport.xml")
        }
        if ($GenerateDeployScript)
        {
            Write-Verbose $script:LocalizedData.PublishUnpublishDacPac.Verbose.DeployScript
            $DacService.GenerateDeployScript($DacPac, $DacProfile.TargetDatabaseName, $DacProfile.DeployOptions) | Out-File (Join-Path $OutputPath "$($DacProfile.TargetDatabaseName).DeployScript.sql")
        }

        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.DeployDacPac -f $DacPac.Name)
        if ($Force -or $PSCmdlet.ShouldProcess($DacProfile.TargetDatabaseName)) { $DacService.Deploy($DacPac, $DacProfile.TargetDatabaseName, $true, $DacProfile.DeployOptions) }
    }
    catch
    {
        Write-Error $_
    }
    finally
    {
        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.ReportPath -f $OutputPath)
        Write-Debug ($script:LocalizedData.Global.Debug.Leaving -f $PSCmdlet.MyInvocation.MyCommand)
    }
}
tools\Bca.Dac\Public\Set-DacDllPath.ps1
function Set-DacDllPath
{
    <#
        .SYNOPSIS
            Sets the path of the DAC DLL.
        .DESCRIPTION
            Sets the path of the DAC DLL.
        .PARAMETER Path
            A string containing the path to either the directory where the DLL is located, or the path to the DLL
        .EXAMPLE
            Set-DacDllPath -Path "C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\Microsoft.SqlServer.Dac.dll"

            Description
            -----------
            This example will return set the DLL path to "C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\Microsoft.SqlServer.Dac.dll".
        .LINK
            Get-DacDllPath
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path $_ } )]
        [string] $Path
    )

    try
    {
        Write-Debug ($script:LocalizedData.Global.Debug.Entering -f $PSCmdlet.MyInvocation.MyCommand)
        $DllPath = Get-Item $Path
        if ($DllPath.PSIsContainer)
        {
            Write-Verbose ($script:LocalizedData.SetDacDllPath.Verbose.FromDirectory -f $DllPath.FullName)
            $DacDllPath = Join-Path $DllPath.FullName "Microsoft.SqlServer.Dac.dll"
            if ((Test-Path $DacDllPath)) { $script:DacDllPath = $DacDllPath }
            else { Write-Error -Message ($script:LocalizedData.SetDacDllPath.Error.NotFound.Message -f $DllPath.FullName) -Category ObjectNotFound -CategoryActivity $MyInvocation.MyCommand -TargetType $script:LocalizedData.SetDacDllPath.Error.NotFound.Target -TargetName $DllPath.FullName -Exception ObjectNotFoundException }
        }
        elseif ($DllPath.Extension -eq ".dll") { $script:DacDllPath = $DllPath.FullName }
        else { Write-Error -Message ($script:LocalizedData.SetDacDllPath.Error.NotValid.Message -f $DllPath.FullName) -Category InvalidData -CategoryActivity $MyInvocation.MyCommand -TargetType $script:LocalizedData.SetDacDllPath.Error.NotValid.Target -TargetName $DllPath.FullName -Exception InvalidDataException }
    }
    catch
    {
        Write-Error $_
    }
    finally
    {
        Write-Debug ($script:LocalizedData.Global.Debug.Leaving -f $PSCmdlet.MyInvocation.MyCommand)
    }
}
tools\Bca.Dac\Public\Set-SqlProjectVersion.ps1
function Set-SqlProjectVersion
{
    <#
        .SYNOPSIS
            Sets a version in a SQL Project file.
        .DESCRIPTION
            Sets a version in a SQL Project file.
        .PARAMETER Path
            An array of strings containing the paths to the SQL Project files or a folder containing them.
        .PARAMETER Version
            A version containing the version to set.
        .PARAMETER Rescurse
            A switch specifying whether or not to look recursively for SQL Project files if Path is a directory.
        .PARAMETER Force
            A switch specifying whether or not to for the modification, for instance if the file is read-only.
        .EXAMPLE
            Set-SqlProjectVersion -Path C:\MyProject\MyProject.sqlproj -Version 1.0.0

            Description
            -----------
            This example will set the version 1.0.0 to MyProject.sqlproj.
        .EXAMPLE
            Set-SqlProjectVersion -Path C:\MyProject\ -Version 1.0.0 -Recurse

            Description
            -----------
            This example will set the version 1.0.0 to all SQL Project files found recursively in C:\MyProject.
    #>
    [CmdLetBinding()]
    param(
        [parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path $_ })]
        [string[]] $Path,
        [parameter(Mandatory = $true)]
        [version] $Version,
        [parameter(Mandatory = $false)]
        [switch] $Recurse,
        [parameter(Mandatory = $false)]
        [switch] $Force
    )

    try 
    {
        Write-Debug ($script:LocalizedData.Global.Debug.Entering -f $PSCmdlet.MyInvocation.MyCommand)
        $SqlProjs = @()
        $Path | ForEach-Object {
            $Item = Get-Item -Path $_
            if ($Item.PSIsContainer)
            {
                Write-Verbose ($script:LocalizedData.SetSqlProjectVersion.Verbose.Directory -f $Item.FullName, $Recurse)
                $SqlProjs += (Get-ChildItem -Path $Item.FullName -Recurse:$Recurse -Include *.sqlproj).FullName
            }
            elseif ($Item.Extension -eq ".sqlproj")
            {
                Write-Verbose ($script:LocalizedData.SetSqlProjectVersion.Verbose.File -f $Item.FullName)
                $SqlProjs += $Item.FullName
            }
            else { Write-Warning ($script:LocalizedData.SetSqlProjectVersion.Warning.NotSqlProj -f $Item.FullName) }
        }
    
        $SqlProjs | Sort-Object -Unique | Get-Unique | ForEach-Object {
            try
            {
                Write-Verbose ($script:LocalizedData.SetSqlProjectVersion.Verbose.ProcessFile -f $_)
                if ($Force)
                {
                    Write-Verbose $script:LocalizedData.SetSqlProjectVersion.Verbose.ROFlag
                    Set-ItemProperty $_ -Name IsReadOnly -Value $false
                }
                $Xml = [xml](Get-Content $_)
                $Xml.Project.PropertyGroup | ForEach-Object {
                    if ($_.DacVersion) { $_.DacVersion = $Version.ToString() }
                }
                $Xml.Save($_)
                Write-Verbose ($script:LocalizedData.SetSqlProjectVersion.Verbose.VersionUpdated -f $Version.ToString(), $_)
            }
            catch
            {
                Write-Error $_
            }
        }

    }
    catch
    {
        Write-Debug ($script:LocalizedData.Global.Debug.Leaving -f $PSCmdlet.MyInvocation.MyCommand)
    }
    finally
    {

    }
}
tools\Bca.Dac\Public\Unpublish-DacPac.ps1
function Unpublish-DacPac
{
    <#
        .SYNOPSIS
            Unpublishes a DAC package.
        .DESCRIPTION
            Unpublishes a DAC package.
        .PARAMETER Path
            A string containing the path to the DAC package.
        .PARAMETER DacProfilePath
            A string containing the path to the DAC profile.
        .PARAMETER DeployOptions
            A hashtable containing the deployment options to use.
        .PARAMETER Mode
            A string containing the mode used to unregister the DAC package.
        .PARAMETER DacDllPath
            A string containing the path to the DAC DLL.
        .PARAMETER KillSessions
            A switch specifying whether or not to terminate active session on the database if it exists.
        .PARAMETER Force
            A switch specifying whether or not to force the execution (will implicitely enable option KillSessions).
        .EXAMPLE
            Unpublish-DacPac -Path C:\MyProject\MyProject.dacpac -DacProfilePath C:\MyProject\MyProject.publish.xml

            Description
            -----------
            This example will undeploy MyProject.dacpac based on the publish profile MyProject.publish.xml.
        .LINK
            Publish-DacPac
    #>
    [CmdLetBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
    param(
        [parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path $_ } )]
        [alias("DacPacPath")]
        [string] $Path,
        [parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path $_ } )]
        [string] $DacProfilePath,
        [parameter(Mandatory = $false)]
        [ValidateSet("UnregisterDac", "DetachDatabase", "DropDatabase")]
        [alias("DacUninstallMode", "UninstallMode")]
        [string] $Mode = "UnregisterDac",
        [ValidateScript( { Test-Path $_ } )]
        [string] $DacDllPath = (Get-DacDllPath),
        [parameter(Mandatory = $false)]
        [switch] $KillSessions,
        [Parameter(Mandatory = $false)]
        [switch] $Force
    )

    try
    {
        Write-Debug ($script:LocalizedData.Global.Debug.Entering -f $PSCmdlet.MyInvocation.MyCommand)

        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadDll -f $DacDllPath)
        Add-Type -Path $DacDllPath

        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadProfile -f $DacProfilePath)
        $DacProfile = [Microsoft.SqlServer.Dac.DacProfile]::Load($DacProfilePath)
        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadPackage -f $Path)
        $DacPac = [Microsoft.SqlServer.Dac.DacPackage]::Load($Path)
        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.LoadService -f $DacProfile.TargetConnectionString)
        $DacService = New-Object Microsoft.SqlServer.Dac.DacServices $DacProfile.TargetConnectionString

        Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.TstDb -f $DacProfile.TargetDatabaseName)
        Write-Debug $DacProfile.TargetConnectionString
        try
        {
            $DbId = Invoke-Sqlcmd -ConnectionString $DacProfile.TargetConnectionString -Query "SELECT DB_ID('$($DacProfile.TargetDatabaseName)') AS [Id]" -ErrorAction SilentlyContinue
            if ($DbId.Id -eq [DBNull]::Value) { $DbExists = $false }
            else { $DbExists = $true }
        }
        catch
        {
            $DbExists = $false
        }
        Write-Debug $DbExists
        
        if ($DbExists)
        {
            if ($KillSessions)
            {
                Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.KillSessions -f $DacProfile.TargetDatabaseName)
                try { Invoke-Sqlcmd -ConnectionString $DacProfile.TargetConnectionString -Query "DECLARE @SQL nvarchar(1000); SELECT @SQL = COALESCE(@SQL,'') + 'KILL ' + Convert(varchar, session_id) + ';' FROM sys.dm_exec_sessions WHERE database_id = DB_ID('$($DacProfile.TargetDatabaseName)') AND session_id > 8 AND session_id <> @@SPID; EXEC (@SQL)" | Out-Null }
                catch { Write-Warning ($script:LocalizedData.PublishUnpublishDacPac.Warning.CantKillSessions -f $DacProfile.TargetDatabaseName) }
            }

            Write-Verbose ($script:LocalizedData.PublishUnpublishDacPac.Verbose.UnregisterDac -f $DacPac.Name, $Mode)
            if ($Force -or $PSCmdlet.ShouldProcess($DacProfile.TargetDatabaseName))
            { 
                $DacService.Unregister($DacProfile.TargetDatabaseName)
                switch ($Mode)
                {
                    "DetachDatabase" { Invoke-Sqlcmd -ConnectionString $DacProfile.TargetConnectionString -Query "EXEC sp_detach_db $($DacProfile.TargetDatabaseName);" | Out-Null }
                    "DropDatabase" { Invoke-Sqlcmd -ConnectionString $DacProfile.TargetConnectionString -Query "DROP DATABASE $($DacProfile.TargetDatabaseName);" | Out-Null }
                }
            }
        }
        else { Write-Warning ($script:LocalizedData.PublishUnpublishDacPac.Warning.DbDoesntExist -f $DacProfile.TargetDatabaseName) }
    }
    catch
    {
        Write-Error $_
    }
    finally
    {
        Write-Debug ($script:LocalizedData.Global.Debug.Leaving -f $PSCmdlet.MyInvocation.MyCommand)
    }
}
tools\chocolateyInstall.ps1
$ErrorActionPreference = "Stop"

$ModuleName = $env:ChocolateyPackageTitle
$ModuleVersion = $env:ChocolateyPackageVersion
$ModulePath = @()
$PackageParameters = Get-PackageParameters

Remove-Module -Name $ModuleName -Force -ErrorAction SilentlyContinue

if ($PackageParameters.Desktop -or !$PackageParameters.Core)
{
    if ($PSVersionTable.PSVersion -lt [Version]'5.1') { Write-Warning "PowerShell version '$($PSVersionTable.PSVersion.ToString())' is not supported to install this package, at least PowerShell 5.1 must be installed, the module may not work properly." }
    $ModulePath += Join-Path (Join-Path $env:ProgramFiles "WindowsPowerShell\Modules") "$ModuleName\$ModuleVersion"
}
if ($PackageParameters.Core) { $ModulePath += Join-Path (Join-Path $env:ProgramFiles "PowerShell\Modules") "$ModuleName\$ModuleVersion" }

$ModulePath -join "`r`n" | Set-Content (Join-Path $PSScriptRoot "installPath.txt")

$ModulePath | ForEach-Object {
    Write-Verbose "Installation path will be '$_'."

    if ((Test-Path $_))
    {
        Write-Verbose "Removing already installed version."
        Remove-Item -Path $_ -Recurse -Force
    }

    Write-Verbose "Creating folder '$_'."
    New-Item -Path $_ -Force -ItemType Directory | Out-Null

    Write-Verbose "Installing module '$ModuleName' version $ModuleVersion in '$_'."
    Get-ChildItem -Path (Join-Path $PSScriptRoot $ModuleName) | Copy-Item -Destination $_ -Recurse -Container -Force
}

Write-Verbose "Module '$ModuleName' version $ModuleVersion installed."
tools\chocolateyUninstall.ps1
$ErrorActionPreference = "Stop"

$ModuleName = $env:ChocolateyPackageTitle
$ModuleVersion = $env:ChocolateyPackageVersion
$ModulePath = Get-Content (Join-Path $PSScriptRoot "installPath.txt") -ErrorAction SilentlyContinue

Remove-Module -Name $ModuleName -Force -ErrorAction SilentlyContinue

if (!$ModulePath) { Write-Warning "No module path found, '$ModuleName' may have been manually uninstalled." }
$ModulePath | ForEach-Object {
    $ParentModulePath = (Split-Path $_ -Parent)

    Write-Verbose "Module path is '$_'."

    if ((Test-Path $_))
    {
        Write-Verbose "Emtpying directory '$_'."
        Remove-Item -Path $_ -Recurse -Force
    }
    else { Write-Warning "Path '$_' not found, '$ModuleName' may have been manually uninstalled." }
    if ((Test-Path $ParentModulePath) -and ((Get-ChildItem -Path $ParentModulePath | Measure-Object).Count -eq 0))
    {
        Write-Verbose "No file left in '$($ParentModulePath)', removing folder."
        Remove-Item -Path $ParentModulePath -Recurse -Force
    }
}

Write-Verbose "Module '$ModuleName' version $ModuleVersion uninstalled."

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.

Version Downloads Last Updated Status

0.1.0:

  • Publish-DacPac / Unpublish-DacPac: functions to deploy or undeploy a DAC packages;
  • Get-DacDllPath/Set-DacDllPath: functions to get or set the path to the DAC DLL used to deploy or undeploy;
  • Set-SqlProjectVersion: function to set the version in a SQL Project file;
  • Supports Windows, Linux and MacOS;
  • Supports English and French language.

This package has no dependencies.

Discussion for the Bca.Dac Package

Ground Rules:

  • This discussion is only about Bca.Dac and the Bca.Dac 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 Bca.Dac, 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