I have the following very simple PowerShell snippet that just won't work.
The following works
Get-MessageTrace -StartDate $dateStart -EndDate $dateEnd -PageSize 5000 `
-SenderAddress [email protected] `
| where {$_.RecipientAddress -like "*example.com*"} `
| Select-Object SenderAddress, RecipientAddress, Subject
While the following does not work
$dateStart = "03/20/2017"
$dateEnd = "03/27/2017"
Get-MessageTrace -StartDate $dateStart -EndDate $dateEnd -PageSize 5000 `
-SenderAddress [email protected] `
| where {$_.RecipientAddress -like "*example.com*"} `
| Select-Object SenderAddress, RecipientAddress, Subject
Even if I replace the $dateStart
and $dateEnd
with various formats such as MM/dd/yyyy hh:mm:ss.
There is no error, just no results returned, however I've used where
patterns that I know should return something. I've also ran the above (example that doesn't work) using today's date (which is the default when -startdate
and -enddate
are not specified) and that also doesn't work. Even though that is what the working example is effectively using.
So I've narrowed it down to the date but I can't see the problem. If I put in a date string that is wrong that at least gives and error, otherwise nothing. Any pointers?
In your script, you are currently using
Because in this case the values are string of characters, Windows PowerShell will automatically use the
String
data type to store the value, whileGet-MessageTrace
-StartDate
and-EndDate
only takeSystem.DateTime
type variables.You can set the correct type variable by using
Get-Date
like this:Alternatively, you can create new
System.DateTime
object by specifying the type of the variable first and then assign a string value to it (if it is a value that can be cast toSystem.DateTime
):However, I'd prefer
Get-Date
as it makes your script more generalizable. For example you can create a script that always gives you information on last seven days:Additional hint:
You can also use
Get-Date
for figuring out the short date format defined in the Regional Options:It will give you the correct short date pattern you need for your
EndDate
andStartDate
parameters.