Skip to content

Instantly share code, notes, and snippets.

Created December 21, 2022 20:18
What would you like to do?
run a bunch of SQL exports, save to CSV, and ZIP them
# CustInvAll-export.ps1
#Requires -Version 7
#Requires -Modules SqlServer
$dateFmt = 'yyyy-MM-dd'
$sqlServer = "MyServer"
$dbName = "myDB"
$curDate = [DateTime]::Today
$startDate = [DateTime]'01/01/2021'
while ($startDate -lt $curDate) {
$endDate = $startDate.AddMonths(1)
$startDateFmt = $startDate.ToString($dateFmt)
$endDateFmt = $endDate.ToString($dateFmt)
$exportSQL = @"
FROM MyTable
where [INVOICEDATE] >= '$startDateFmt' and [INVOICEDATE] < '$endDateFmt'
$exportFile = "CustInvAll-$startDateFmt.csv"
$exportFileZip = "CustInvAll-$"
echo "Exporting from $startDateFmt to $EndDateFmt to file $exportFile"
# Invoke-Sqlcmd -ServerInstance $sqlServer -Database $dbName -Query $exportSQL `
# | Export-CSV -Path $exportFile -NoTypeInformation -UseQuotes AsNeeded
# Compress-Archive -LiteralPath $exportFile -DestinationPath $exportFileZip
$startDate = $endDate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment