A client had a table which was storing data since 11 years, and he wanted to export all that data into csv files in a chunk of 15 days data per csv file. So I developed a PowerShell script to do the same. Hope it helps in different scenarios.
cls
$OutputDirectory = "Z:\CSV_Extract\" #Specify the desired output directory
[DateTime]$StartDate = '2012-06-27' # Specify the start date for the 15-day slots
[DateTime]$EndDate = '2023-06-10' # Specify the end date for the 15-day slots
[DateTime]$SlotStartDate = $StartDate.ToString('yyyy-MM-dd')
[DateTime]$SlotEndDate = $SlotStartDate.AddDays(14).ToString('yyyy-MM-dd')
$SQLServer = "SQLInstance"
$db = "databaseName"
WHILE ($SlotStartDate -le $EndDate)
{
$CommandText = @"
SELECT * FROM your_Tabe(nolock) WHERE Your_Date_Column>= CONVERT(NVARCHAR(10), '$SlotStartDate', 120) AND Your_Date_Column <= CONVERT(NVARCHAR(10), '$SlotEndDate', 120) order by Your_Date_Column
"@
Write-Host "Fetching Report for $slotStartDate " -ForegroundColor Cyan
$Report = Invoke-Sqlcmd -ServerInstance $SQLServer -Database $db -Query $CommandText
$Csv_Name = "Z:\CSV_Extract\"+$SlotStartDate.ToString('yyyy-MM-dd')
$Report | Export-CSV -Path "$Csv_Name.csv"
$SlotStartDate = $SlotStartDate.AddDays(15).ToString('yyyy-MM-dd')
$SlotEndDate = $SlotEndDate.AddDays(15).ToString('yyyy-MM-dd')
}