Skip to content

Instantly share code, notes, and snippets.

@adtraub
Last active October 14, 2016 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adtraub/0f8691cef585475e6c60cd53ed730afb to your computer and use it in GitHub Desktop.
Save adtraub/0f8691cef585475e6c60cd53ed730afb to your computer and use it in GitHub Desktop.
Two powershell functions for running SQL. The first runs a single file, the second runs all files within a directory.
#Runs A SQL Script
Function runSQLScript {
param(
[string]$db, # the sql db to use
[string]$script, #the script to use
[string]$outLog,
[string]$errLog
)
if($db){#The things I do for pretty output...
$db = " $db"
}
Write-Host "`nBegin SQL Processing of:$db $script`t$(currentUDate)"
if($db){
$db = "-d$db"
}
SQLCMD -E $db -i $script -r1 2>> $errLog 1>> $outLog
};
#Run all SQL Scripts within a directory
Function runAllSQLScripts {
param(
[string]$db, # the sql db to use
[string]$dir = (Get-Item -Path ".\" -Verbose).FullName, # the directory to to run all sql files in, defaults to CWD. if you want to speci
[string]$filter = '*.sql' #just incase someone wants to change the filter
)
$currDate = $(currentUDate)
$outLog = "out.$currDate.log"
$errLog ="err.$currDate.log"
$files = Get-ChildItem $dir -Filter *.sql
ForEach ($file in $files){
runSQLScript -db $db -script $dir\$file -outLog $outLog -errLog $errLog
}
};
//unix epoch timestamp
Function currentUDate{
return $([string]$(Get-Date -UFormat %s)).split('.')[0]
};
@adtraub
Copy link
Author

adtraub commented Oct 13, 2016

Added a bonus timestamp utility function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment