Skip to content

Commit 1ce0267

Browse files
author
Calvin Tapp
committed
New Publish-DacPac function, documentation fixes
1 parent fddae56 commit 1ce0267

File tree

3 files changed

+148
-2
lines changed

3 files changed

+148
-2
lines changed
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
<#
2+
.SYNOPSIS
3+
Will Invoke DacPac utilising sqlpackage.exe
4+
5+
.DESCRIPTION
6+
Deploy a dacpac against specified instance of SQL Server Using psobject where Property is name of variable/parameter and value is the desired value.
7+
The 'DefaultFilePrefix' is always the value of TargetDatabase parameter.
8+
9+
.PARAMETER SqlServerName
10+
Name of the SQL Server. populates /TargetServerName:
11+
12+
.PARAMETER TargetDatabase
13+
Defines the target database and will also be utilised for the the /v:DefaultFilePrefix
14+
15+
.PARAMETER SourceFile
16+
Full Path to the .dacpac file to be published. Populates /SourceFile:
17+
18+
.PARAMETER Properties
19+
[Hashtable] Where property is name of parameter with its value.
20+
21+
.PARAMETER Variables
22+
[Hashtable] Object of variables with property name of var and value is input.
23+
24+
.EXAMPLE
25+
$prop = @{BlockOnPossibleDataLoss = $true; BlockWhenDriftDetected = $false; CreateNewDatabase = $false; TreatVerificationErrorsAsWarnings = $true }
26+
$vars = @{Variable1 = "Dev"; foo="bar" }
27+
Publish-DacPac -SqlServername 'localhost\SQLEXPRESS' -TargetDatabase "TestDb" -SourceFile "C:\Staging\TestDb\TestDb.dacpac" -Properties $prop -Variables $vars
28+
29+
Will publish dacpac Testdb to localhost\SQLEXPRESS.
30+
31+
.NOTES
32+
Requires sqlpackage.exe to be installed on executing machine within Program Files(x86), with administrator rights on database server.
33+
#>
34+
function Publish-DacPac {
35+
param (
36+
[Parameter(Mandatory = $true, position = 0, HelpMessage = "Name of the SQL Server Instance.", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)]
37+
[string]$SqlServerName,
38+
39+
[Parameter(Mandatory = $true, position = 1, HelpMessage = "Name of Target Database", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)]
40+
[string] $TargetDatabase,
41+
42+
[Parameter(Mandatory = $true, position = 2, helpmessage = "Full path to Dacpac file.")]
43+
[ValidateScript( {
44+
if (-not (Test-Path $_)) {
45+
throw "File does not exist"
46+
}
47+
if (-not(Test-Path $_ -pathtype leaf)) {
48+
throw "The path argument must be a file. Folder paths are not allowed."
49+
}
50+
if ($_.Extension -ne '.dacpac') { throw "The file specified in the path must be of type dacpac." }
51+
return $true
52+
})]
53+
[System.IO.FileInfo]$SourceFile,
54+
55+
[Parameter(Mandatory = $true, position = 3, helpmessage = "PSObject containing Parameters for the dacpac to utilise.")]
56+
[ValidateScript( {
57+
if ($_.Keys.Count -le 0) { throw "[hashtable] 'Parameters' must have atleast one key value pair" }else { return $true }
58+
})]
59+
[hashtable]$Properties,
60+
61+
[Parameter(mandatory = $true, position = 4, helpmessage = "PSObject containing variables for dacpac")]
62+
[ValidateScript( {
63+
if ($_.Keys.Count -le 0) { throw "[hashtable] 'Variables' must have atleast one key value pair" }else { return $true }
64+
})]
65+
[hashtable]$Variables
66+
)
67+
68+
begin {
69+
70+
#Validate all keys provided are of valid Parameters for publish action case-sensitive
71+
$validProperties = @("AdditionalDeploymentContributorArguments", "AdditionalDeploymentContributors",
72+
"AllowDropBlockingAssemblies", "AllowIncompatiblePlatform", "AllowUnsafeRowLevelSecurityDataMovement", "BackupDatabaseBeforeChanges", "BlockOnPossibleDataLoss", "BlockWhenDriftDetected",
73+
"CommandTimeout", "CommentOutSetVarDeclarations", "CompareUsingTargetCollation", "CreateNewDatabase", "DeployDatabaseInSingleUserMode", "DisableAndReenableDdlTriggers", "DoNotAlterChangeDataCaptureObjects",
74+
"DoNotAlterReplicatedObjects", "DoNotDropObjectType", "DoNotDropObjectTypes", "DropConstraintsNotInSource", "DropDmlTriggersNotInSource", "DropExtendedPropertiesNotInSource", "DropIndexesNotInSource",
75+
"DropObjectsNotInSource", "DropPermissionsNotInSource", "DropRoleMembersNotInSource", "DropStatisticsNotInSource", "ExcludeObjectType", "ExcludeObjectTypes", "GenerateSmartDefaults", "IgnoreAnsiNulls", "IgnoreAuthorizer", "IgnoreColumnCollation", "IgnoreColumnOrder",
76+
"IgnoreComments", "IgnoreCryptographicProviderFilePath", "IgnoreDdlTriggerOrder", "IgnoreDdlTriggerState", "IgnoreDefaultSchema", "IgnoreDmlTriggerOrder", "IgnoreDmlTriggerState", "IgnoreExtendedProperties",
77+
"IgnoreFileAndLogFilePath", "IgnoreFilegroupPlacement", "IgnoreFileSize", "IgnoreFillFactor", "IgnoreFullTextCatalogFilePath", "IgnoreIdentitySeed", "IgnoreIncrement", "IgnoreIndexOptions",
78+
"IgnoreIndexPadding", "IgnoreKeywordCasing", "IgnoreLockHintsOnIndexes", "IgnoreLoginSids", "IgnoreNotForReplication", "IgnoreObjectPlacementOnPartitionScheme", "IgnorePartitionSchemes",
79+
"IgnorePermissions", "IgnoreQuotedIdentifiers", "IgnoreRoleMembership", "IgnoreRouteLifetime", "IgnoreSemicolonBetweenStatements", "IgnoreTableOptions", "IgnoreUserSettingsObjects", "IgnoreWhitespace",
80+
"IgnoreWithNocheckOnCheckConstraints", "IgnoreWithNocheckOnForeignKeys", "IncludeCompositeObjects", "IncludeTransactionalScripts", "NoAlterStatementsToChangeClrTypes", "PopulateFilesOnFileGroups",
81+
"RegisterDataTierApplication", "RunDeploymentPlanExecutors", "ScriptDatabaseCollation", "ScriptDatabaseCompatibility", "ScriptDatabaseOptions", "ScriptDeployStateChecks",
82+
"ScriptFileSize", "ScriptNewConstraintValidation", "ScriptRefreshModule", "Storage", "TreatVerificationErrorsAsWarnings", "VerifyCollationCompatibility", "VerifyDeployment"
83+
)
84+
85+
foreach ($key in $Properties.Keys) {
86+
if ($validProperties -cnotcontains $key) {
87+
throw "Property '$($key)' is not a valid Property for sqlpackage.exe, Do note this is case sensitive."
88+
}
89+
}
90+
91+
$exe = Get-SqlPackage
92+
if ($null -ne $exe) {
93+
Set-Alias -name sqlpackage -value $exe
94+
}
95+
else {
96+
throw "Unable to locate sqlpackage.exe"
97+
}
98+
99+
$args = "sqlpackage /a:Publish /sf:`"$SourceFile`" /tsn:`"$SqlServerName`" /tdn:`"$TargetDatabase`" /v:`"DefaultFilePrefix`"=`"$TargetDatabase`""
100+
}
101+
102+
process {
103+
104+
foreach ($key in $Properties.Keys) {
105+
$value = $Properties[$key]
106+
$args += " /p:`"$key`"=`"$value`""
107+
}
108+
109+
foreach ($key in $Variables.Keys) {
110+
$value = $Variables[$key]
111+
$args += " /v:`"$key`"=`"$value`""
112+
}
113+
114+
Invoke-Expression $args
115+
}
116+
}

CommonFunctions/Public/Show-ConfirmationPrompt.ps1

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
.DESCRIPTION
55
Will prompt user for confirmation expecting y/n answer and returning that as a boolean
66
.PARAMETER Message
7-
The text that should be shown will be appended with (Y/N) ?
7+
The text that should be shown will be appended with ' (Y/N) ?'
88
.EXAMPLE
99
Show-ConfirmationPrompt "Do you wish to continue"
10-
Will display as Do you wich to contine (Y/N) ?
10+
11+
Will display as 'Do you wish to contine (Y/N) ?'
1112
returns $true if Y/y otherwise $false
1213
#>
1314
function Show-ConfirmationPrompt {

CommonFunctions/Public/Write-Log.ps1

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,32 @@
1+
<#
2+
.SYNOPSIS
3+
Will write string input to logfile provided, with formatted date time and log level.
4+
.DESCRIPTION
5+
Will write a message to the logfile provided if doesn't exist will create then append from then on.
6+
Will display the message with execution timestamp (UK format) and loglevel
7+
8+
This also has the option to print the same message to the host simultaneously
9+
.PARAMETER Level
10+
Log Level, default is 'INFO'
11+
.PARAMETER Message
12+
Message that should be printed
13+
.PARAMETER LogFile
14+
Path to the logfile, should end with .txt or .log
15+
.PARAMETER AndTerminal
16+
If provided, will also print the formatted log entry to current execution host instance.
17+
.EXAMPLE
18+
Write-Log -Level ERROR -Message "Cannot find the file you specified" -LogFile C:\Logs\log.txt
19+
Will write the message to the logfile provided
20+
21+
.EXAMPLE
22+
Write-Log -Message "Starting Foo..." -LogFile C:\Logs\FooLog.log -AndTerminal
23+
Will write "<timestamp> [INFO] Starting Foo..." to logfile specified and also to screen.
24+
25+
.NOTES
26+
Work in progress, can definitly be improved...
27+
1. Add ability to recieve input from pipe, in order to support redirecting to well formed log
28+
2. Invoke some checking to ensure that the logfile is in .txt or .log format
29+
#>
130
function Write-Log {
231
param (
332
[Parameter(Mandatory=$false)]

0 commit comments

Comments
 (0)