The problem is that you're calling the script using a string
Invoke-Expression "C:\MoveAndDeleteFolder.ps1 -startDate $startDate -endDate $endDate"
$startdate and $enddate contains a whitespace between the date and time, so when it's parsed, the date is considered the value of the parameter, but because of the whitespace, the time is considered an argument. The sample below shows this.
test1.ps1:
param
(
[Datetime]$startDate,
[Datetime]$endDate
)
$startDate| Write-Output
"Args:"
$args
Script:
$startDate = "02/05/2015 19:00"
$endDate = "02/06/2015 14:15"
Write-Host "c:\test.ps1 -startDate $startDate -endDate $endDate"
Invoke-Expression "c:\test.ps1 -startDate $startDate -endDate $endDate"
Output:
#This is the command that `Invoke-Expression` runs.
c:\test.ps1 -startDate 02/05/2015 19:00 -endDate 02/06/2015 14:15
#This is the failed parsed date
5. februar 2015 00:00:00
Args:
19:00
14:15
There are two solutions here. You could run the script directly without Invoke-Expression and it will send the objects properly.
c:\test.ps1 -startDate $startDate -endDate $endDate
Output:
c:\test.ps1 -startDate 02/05/2015 19:00 -endDate 02/06/2015 14:15
5. februar 2015 19:00:00
Or you could quote $startDate and $endDate in your expression-string, like:
Invoke-Expression "C:\MoveAndDeleteFolder.ps1 -startDate '$startDate' -endDate '$endDate'"