Solved

Powershell Script: SQL Query Comparing Dates

Posted on 2013-01-17
10
1,176 Views
Last Modified: 2013-01-17
Within my SQL table I have a date field that lists the date the record was created. I only want to process records where the date is 90 days earlier than the current date.

$d=(Get-Date).adddays(-90)   shows the following format: 10/19/2012 1:07:40 PM

However the table I'm working with has about 8000 records and the date is in this format: 2012-10-19 00:00:00.000

If I use: $SqlQuery = "SELECT UserName from TermEmp_Test WHERE DisableDate<'20012-10-19 00:00:00.000'"      The script works fine.  

Attempting date comparison throws the following:

Old Date: 10/19/2012 1:29:16 PM

ERROR: Exception calling "Fill" with "1" argument(s) "Incorrect Syntax near '13'."
ERROR: At Line 47 char 17
ERROR: + $SqlAdapter.Fill <<<<<($DataSet) | Out-Null
ERROR:      +Category Info                  : Not Specified: (:) [], MethodInvocationException
ERROR:       +Fully Qualified Error ID  : DotNetMethodException
ERROR:

****PowerShell Script Finished. *****

I really need the comparison to work and I'm not sure if it's the difference in the format or the statement itself.

Thanks,

JB

$d=(Get-Date).adddays(-90)
Write-Host "Old Date: " $d

#$SqlQuery = "SELECT UserName from TermEmp_Test WHERE DisableDate<'2012-10-19 00:00:00.000'"

$SqlQuery = "SELECT * from TermEmp_Test WHERE DisableDate<#$d#"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"

#Instantiates the Command Object
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand

#Command Text Using Variable
$SqlCmd.CommandText = $SqlQuery

#Create Connection
$SqlCmd.Connection = $SqlConnection

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd

$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) | Out-Null

#Populate Hash Table
$objTable = $DataSet.Tables[0]

#Populate Hash Table, and export to CSV File
#$DataSet.Tables[0] | Export-Csv -NoTypeInformation $AttachmentPath

#Populate Hash Table, export to CSV, and change column headers
$DataSet.Tables[0] | select @{l='Alias'; e={$_.Username}} | Export-Csv -NoTypeInformation $AttachmentPath

$SqlConnection.Close()
0
Comment
Question by:JB4375
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +2
10 Comments
 
LVL 40

Expert Comment

by:lcohan
ID: 38788725
"If I use: $SqlQuery = "SELECT UserName from TermEmp_Test WHERE DisableDate<'20012-10-19 00:00:00.000'"      The script works fine."

that means in my opinion that your TermEmp_Test.DisableDate is DATE data type (no time portion) so you would need to convert your $d=(Get-Date).adddays(-90) as DATE not DATETIME format - drop the time portion of it
0
 
LVL 5

Expert Comment

by:coraxal
ID: 38788827
Try converting your reference date
From this:

$d=(Get-Date).adddays(-90)

To this:


$d = (Get-Date).adddays(-90).ToString('yyyy-MM-dd HH:mm:ss')

Open in new window


I think I've something something similar for MySQL before.
0
 
LVL 1

Author Comment

by:JB4375
ID: 38788999
Coraxal and lcohan:

I tried: $d = (Get-Date).adddays(-90).toshortdatestring() before posting here, resulting in the same error above but specifically pointing to the '#' on DisableDate<#$d#.

Using $d = (Get-Date).adddays(-90).ToString('yyyy-MM-dd HH:mm:ss') gets the same error that I posted originally.

As did:
$d = (Get-Date).adddays(-90).ToString('yyyy-MM-dd')
$d = $d + " 00:00:00.000"

which looks exactly like what I'm comparing.

Question: Just throwing ideas around but is it possible to select the row of data, and strip the " 00:00:00.000" from the end before doing the comparison?
0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 5

Expert Comment

by:coraxal
ID: 38789160
Just curious...have you tried the .ToShortDateString()?
$d = (Get-Date).AddDays(-90).ToShortDateString()

Open in new window

0
 
LVL 70

Accepted Solution

by:
Qlemo earned 500 total points
ID: 38789296
Your are not using
   $SqlQuery = "SELECT * from TermEmp_Test WHERE DisableDate<#$d#"
I hope! MSSQL doesn't like number signs as delimiters. You would have to use single quotes, and the "yyyy-mm-hh" date format:
$d = (Get-Date).adddays(-90).ToString('yyyy-MM-dd')
$SqlQuery = "SELECT * from TermEmp_Test WHERE DisableDate< '$d' "

Open in new window

Providing the time portion of 0:0:0 is optional.
0
 
LVL 40

Expert Comment

by:Subsun
ID: 38789338
You can check this and see if it works..
$d = (Get-Date).adddays(-90).tostring("MM-dd-yyyy hh:mm:ss.fff")
$SqlQuery = "SELECT * from TermEmp_Test WHERE DisableDate<'$d'"

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
ID: 38789383
Never mind, Qlemo has already posted the same suggestion..Next time I will refresh the page before posting the comment.. :-)
0
 
LVL 1

Author Closing Comment

by:JB4375
ID: 38789388
Thanks again Qlemo.

Gonna have to see about putting you on retainer.  ;^)
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 38789748
I'm sooo happy I have been faster than Subsun this time :p
0
 
LVL 40

Expert Comment

by:Subsun
ID: 38789822
Guess I forgot to take my Superman pill this morning... ;-)
0

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question