Public/InstallHelpers/Install.Database.Functions.psm1
Set-StrictMode -Version Latest $ErrorActionPreference = "Stop"; #Requires -Version 5.0 function _loadDbaTools() { [string] $originalLocation = (Get-Location).Path Set-Location $PSScriptRoot $scriptRootParent = (Get-Item .).Parent.FullName Import-Module "$scriptRootParent\ModuleHelpers\Module.Functions.psm1" LoadModule -moduleNameOrPath 'dbatools' -installViaNuGet $true return $originalLocation } # NOTE: This function depends on the dbatools module # TODO: Ensure dbatools is installed/loaded prior in this function function DropDatabase( [Parameter(mandatory=$true)] [System.Management.Automation.PSCredential] $credential, [Parameter(mandatory=$true)] [string] $dbHost, [Parameter(mandatory=$true)] [string] $dbName ) { # TODO: Can I Parameterize this? (I don't think so...) [string] $dropDbSql = @" USE [master] GO IF DB_ID('$dbName') IS NOT NULL BEGIN DROP DATABASE [$dbName] END "@ # DOCS: https://docs.dbatools.io/#Invoke-DbaQuery $result = Invoke-DbaQuery ` -SqlInstance $dbHost ` -Query $dropDbSql ` -SqlCredential $credential Write-Host $result # TODO: Handle errors with exit 1 } # TODO: Stronly typed hash table: New-Object 'System.Collections.Generic.Dictionary[string,int]' # EX ARGS FOR PARAMS: -Query 'SELECT * FROM users WHERE Givenname = @name' -SqlParameters @{ Name = "Maria" } function RunSql( # EX: @{ SqlInstance = $Env:ComputerName; Query = 'SELECT 1' } [Parameter(mandatory=$true)] [System.Collections.Hashtable] $dbaQueryParams ) { [string] $originalLocation = _loadDbaTools $result = @{} try { # DOCS: https://docs.dbatools.io/#Invoke-DbaQuery # NOTE: We're using splatting below (https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-5.1) $queryResult = Invoke-DbaQuery @dbaQueryParams $result['QueryResult'] = $queryResult $result['ExitCode'] = 0 # TODO: Handle errors with exit 1? } catch { Write-Host -ForegroundColor Red $_ $result['QueryResult'] = '' $result['ExitCode'] = 1 } finally { # INTENT: Avoid interfering with work directories in consuming scripts Set-Location $originalLocation } return $result } # NOTE: This should be kept in sync with encryption used by consumers function EncryptData( [Parameter(mandatory=$true)] [string] $data ) { [byte[]] $secretKey = @(31, 22, 5, 32, 25, 16, 37, 28) [byte[]] $initVector = @(10, 20, 30, 40, 50, 60, 70, 80) [byte[]] $inputBuffer = [System.Text.Encoding]::Unicode.GetBytes($data) $outputBuffer = [System.Security.Cryptography.DES]::Create().CreateEncryptor( $secretKey, $initVector ).TransformFinalBlock( $inputBuffer, 0, $inputBuffer.Length ) return [System.Convert]::ToBase64String($outputBuffer) } Export-ModuleMember -Function "*" |