Core component of SQL Server for storing, processing, and securing data
Step 1: Create the PowerShell script (Export-Query.ps1)
# Parameters
$SqlServer = "YOUR_SQL_SERVER_NAME"
$Database = "lc_V3"
$OutputFile = "C:\Exports\Products.csv"
# SQL Query
$Query = @"
SELECT
Items.iID AS product_id,
LTRIM(RTRIM(s.ProductNumber)) AS mpn
FROM Items
LEFT JOIN POS..Skus s ON Items.strSku = s.Sku
WHERE ISNULL(LTRIM(RTRIM(s.ProductNumber)), '') <> '';
"@
# Load SQL client
$connectionString = "Server=$SqlServer;Database=$Database;Integrated Security=True;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $Query
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
$table = New-Object System.Data.DataTable
# Fill table with results
$adapter.Fill($table) | Out-Null
# Export to CSV with headers
$table | Export-Csv -Path $OutputFile -NoTypeInformation -Encoding UTF8
Write-Host "Export completed: $OutputFile"
Step 2: Run the script
- Save the script as
Export-Query.ps1. - Run it manually first:
powershell.exe -ExecutionPolicy Bypass -File "C:\Path\Export-Query.ps1"
Step 3: Automate with Task Scheduler
- Open Task Scheduler.
- Create a new task → Trigger it (daily, hourly, etc.).
- Action → Start a Program →
Program:
powershell.exeArguments:-ExecutionPolicy Bypass -File "C:\Path\Export-Query.ps1"
If your SQL login uses SQL authentication instead of Windows Auth, change the connection string:
$connectionString = "Server=$SqlServer;Database=$Database;User Id=USERNAME;Password=PASSWORD;"
Make sure the folder C:\Exports\ exists (or update $OutputFile path).
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin