commit 32b902565dbdfb200381f7af4ce4671819fc5424 Author: Frank Bischof Date: Wed Apr 5 11:53:25 2023 +0200 Initial release diff --git a/README.md b/README.md new file mode 100644 index 0000000..fa1910d --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +# Monthly SQL Query automation + +## Description +You can set the DB server and database in the config part of the script. +You can specify settings: +``` +$SQLServer = "dbserver1" +$SQLDBName = "database" +$delimiter = ";" +``` + +The SQL files queried for are: +``` +$SqlFile = 'Query file 1' +$SqlFile = 'Query file 2' +$SqlFile = 'Query file 3' +``` +These SqlFiles corespond to ea. "Query file 1.sql" and will be output to 'YYYYMMDD/Query File 1.csv' +The script uses your windows credentials to log in to the server and execute the queries. \ No newline at end of file diff --git a/monthly_sql_queries.ps1 b/monthly_sql_queries.ps1 new file mode 100644 index 0000000..586cee5 --- /dev/null +++ b/monthly_sql_queries.ps1 @@ -0,0 +1,47 @@ +# VERSION: 1.4.0 +# AUTHOR: F. Bischof (info@meer-web.nl) + +#Variable to hold variable +$SQLServer = "dbserver1" +$SQLDBName = "database" +$delimiter = ";" + +#### Start script #### +# Function to log to file +Function SetLog { + $DATUM = Get-Date -UFormat "%d-%m-%Y %H:%M:%S" + "${DATUM}: ${LogMsg}" | Out-File -Append -FilePath ${LogFile} +} + + +# Check Powershell version 7 +if (($PSVersionTable.PSVersion.Major) -ne 7) { Write-Host "Please use Powershell 7"; exit } +# Check if SqlServer module is installed +if ($null -eq ((Get-InstalledModule).Name | select-string -Pattern "SqlServer")) { Install-Module -Name SqlServer } +$Location = (Get-Location).path +$TimeStamp = (get-date).ToString("yyyyMMdd-HHmm") +$LogFile = "$Location\$TimeStamp\SqlDump.log" +mkdir ${TimeStamp} +Write-Host "=== STARTING QUERIES ON $SQLDBName ===" +$LogMsg = "Starting queries on $SQLDBName"; SetLog + +function SqlQueryExec { + #SQL Query + Write-Host "Starting - ${SqlFile}" + $LogMsg = "- $SqlFile"; SetLog + if ($true -eq (test-path -path "${SqlFile}.sql")) { + $SqlResult = Invoke-Sqlcmd -InputFile "${SqlFile}.sql" -ServerInstance $SQLServer -Database $SQLDBName -QueryTimeout 0 -TrustServerCertificate + $SqlResult | Export-CSV -Path "$Location\$TimeStamp\${SqlFile}.csv" -Delimiter $delimiter -NoTypeInformation + Write-Host "Done - ${SqlFile}" + } else { + Write-Host "ERROR - ${SqlFile}.sql does not exist!" + exit + } +} + +$SqlFile = 'APS Query CRS_v3'; SqlQueryExec +$SqlFile = 'Query Aanspraken GP v3'; SqlQueryExec +$SqlFile = 'Query Basis GP v2'; SqlQueryExec +$SqlFile = 'Query Memoveld v2'; SqlQueryExec + +$LogMsg = "Done!"; SetLog