0

In a powershell script, I try to call another script with two datetime parameters.

Parent script :

$startDate = "02/05/2015 19:00"
$endDate = "02/06/2015 14:15"

Invoke-Expression "C:\MoveAndDeleteFolder.ps1 -startDate $startDate -endDate $endDate"

Child script :

param
(
    [Datetime]$startDate,
    [Datetime]$endDate
)

$startDate| Write-Output

Result :

Tuesday February, the 10th 2015 00:00:00

-> The time is lost !

Does anybody know why ?

0

2 Answers 2

2

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'"
Sign up to request clarification or add additional context in comments.

1 Comment

Honestly, I never understood why people are so keen on using Invoke-Expression. It's only very rarely needed (same as with eval, which it practically is, in many other languages). It only complicates matters, throws away every benefit PowerShell has over simpler shells and almost never is a solution to a problem (just another problem).
1

Or try this:

Invoke-Expression "C:\MoveAndDeleteFolder.ps1 -startDate `"$startDate`" -endDate `"$endDate`""

1 Comment

Wow. I didn't notice the space. That's..... embarrassing. Good catch. :) Would still recommend to avoid Invoke-Expression though. At least the provided sample doesn't need it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.