I have a SQL Query that I am trying to add to Powershell so that I can setup a routine to export a CSV file. The SQL works great:
declare @firstdayfilter datetime;
declare @lastdayfilter datetime;
declare @SalesDate date;
set @firstdayfilter = (select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0));
set @lastdayfilter = (SELECT DATEADD(DAY, -(DAY(GETDATE())), GETDATE()));
set @SalesDate = (select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0));
select @firstdayfilter ,@lastdayfilter ,@SalesDate
When I move this into a Powershell file, I get an error when I try to declare the variable. I've tried many different iterations to no success. I am a noob at Powershell.
Here's what I had originally (for the first field).
$FirstDayFilter = @"
Declare @firstdayfilter datetime ;
set @firstdayfilter = (select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0));
"@
$SqlQuery = @"
SELECT
$FirstDayFilter
"@
This is the error message I get:
Exception calling "Fill" with "1" argument(s): "Incorrect syntax near the keyword
'Declare'."
At S:\Common\Active IT Projects\Projects\OrionSales\OrionCPIMTDSalesReport.ps1:277 char:5
+ $SqlAdapter.Fill($DataSet) #| Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
So what am I missing? I know other fields work. For example if I set $FirstDayFilter = "Test" it works.