core/sql/Invoke-Sql.ps1
<#
The MIT License (MIT) Copyright (c) 2015 Objectivity Bespoke Software Specialists 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. #> function Invoke-Sql { <# .SYNOPSIS Runs a T-SQL script using .NET classes (default, no prerequisites needed) or sqlcmd.exe. .DESCRIPTION Runs sql command or sql script file .PARAMETER ConnectionString Connection string. .PARAMETER Query Sql queries that will be run. .PARAMETER InputFile File(s) containing sql query to run. .PARAMETER Mode Determines how the sql is run - by sqlcmd.exe or .NET SqlCommand. .PARAMETER SqlCommandMode Sql command mode to use if Mode = .net (NonQuery / Scalar / Dataset). Ignored if mode is different than .net. .PARAMETER IgnoreErrors If set ignore errors when sqlcmd.exe is running .PARAMETER QueryTimeoutInSeconds Query timeout. .PARAMETER ConnectTimeoutInSeconds Connect timeout. .PARAMETER SqlCmdVariables Hashtable containing sqlcmd variables. .PARAMETER SqlParameters Array of SqlParameters for .NET SqlCommand. .PARAMETER Credential Credential to impersonate in Integrated Security mode. .PARAMETER DatabaseName Database name to use, regardless of Initial Catalog settings in connection string. Can also be used to remove database name from connection string (when passed empty string). .OUTPUTS String if Mode = sqlcmd. System.Data.DataSet if Mode = .net. .EXAMPLE Invoke-Sql -ConnectionString $connectionString -Sql $Query-TimeoutInSeconds -SqlCmdVariables $param #> [CmdletBinding()] [OutputType([object])] param( [Parameter(Mandatory=$true)] [string] $ConnectionString, [Parameter(Mandatory=$false)] [string[]] $Query, [Parameter(Mandatory=$false)] [string[]] $InputFile, [Parameter(Mandatory=$false)] [string] [ValidateSet($null, 'sqlcmd', '.net')] $Mode = '.net', [Parameter(Mandatory=$false)] [string] [ValidateSet($null, 'NonQuery', 'Scalar', 'Dataset')] $SqlCommandMode = 'Dataset', [Parameter(Mandatory=$false)] [bool] $IgnoreErrors, [Parameter(Mandatory=$false)] [int] $QueryTimeoutInSeconds = 3600, [Parameter(Mandatory=$false)] [int] $ConnectTimeoutInSeconds = 60, [Parameter(Mandatory=$false)] [hashtable] $SqlCmdVariables, [Parameter(Mandatory=$false)] [Data.SqlClient.SqlParameter[]] $SqlParameters, [Parameter(Mandatory=$false)] [PSCredential] $Credential, [Parameter(Mandatory=$false)] [string] $DatabaseName ) if (!$Mode) { $Mode = '.net' } if (!$Query -and !$InputFile) { throw 'Missing -Query or -InputFile parameter' } if ($Mode -eq 'sqlcmd') { $sqlCmdPath = Get-CurrentSqlCmdPath if (!$sqlCmdPath) { Write-Log -Warn 'Cannot find sqlcmd.exe - falling back to .NET' $Mode = '.net' } } if ($InputFile) { foreach ($file in $Inputfile) { if (!(Test-Path -LiteralPath $file)) { throw "$InputFile does not exist. Current directory: $(Get-Location)" } } } $csb = New-Object -TypeName System.Data.SqlClient.SqlConnectionStringBuilder -ArgumentList $ConnectionString if ($PSBoundParameters.ContainsKey('DatabaseName')) { $csb.set_InitialCatalog($DatabaseName) } $params = @{ ConnectionStringBuilder = $csb IgnoreErrors = $IgnoreErrors QueryTimeoutInSeconds = $QueryTimeoutInSeconds ConnectTimeoutInSeconds = $ConnectTimeoutInSeconds SqlCmdVariables = $SqlCmdVariables Credential = $Credential } $targetLog = "$($csb.DataSource)" if ($csb.InitialCatalog) { $targetLog += " / $($csb.InitialCatalog)" } if ($Mode -eq 'sqlcmd') { foreach ($q in $Query) { $params['Query'] = $q if ($q.Trim().Length -gt 40) { $qLog = ($q.Trim().Substring(0, 40) -replace "`r", '' -replace "`n", '; ') + '...' } else { $qLog = $q.Trim() } Write-Log -_Debug "Running custom query at $targetLog using sqlcmd, QueryTimeout = $QueryTimeoutInSeconds s (${qLog}...)" Invoke-SqlSqlcmd @params } [void]($params.Remove('Query')) foreach ($file in $InputFile) { $file = (Resolve-Path -LiteralPath $file).ProviderPath $params['InputFile'] = $file Write-Log -_Debug "Running sql file '$file' at $targetLog using sqlcmd, QueryTimeout = $QueryTimeoutInSeconds s" Invoke-SqlSqlcmd @params } } elseif ($Mode -eq '.net') { $params['Mode'] = $SqlCommandMode $params['SqlParameters'] = $SqlParameters foreach ($q in $Query) { $params['Query'] = $q if ($q.Trim().Length -gt 40) { $qLog = ($q.Trim().Substring(0, 40) -replace "`r", '' -replace "`n", '; ') + '...' } else { $qLog = $q.Trim() } Write-Log -_Debug "Running custom query at $targetLog using .Net (${qLog})" Invoke-SqlDotNet @params } foreach ($file in $InputFile) { $file = (Resolve-Path -LiteralPath $file).ProviderPath Write-Log -_Debug "Running sql file '$file' at $targetLog using .Net, QueryTimeout = $QueryTimeoutInSeconds s" $params['Query'] = Get-Content -LiteralPath $file -ReadCount 0 | Out-String Invoke-SqlDotNet @params } } else { throw "Unrecognized mode: ${Mode}." } } |