将日期时间传递给 powershell 脚本

Pass Datetime to powershell script

在 powershell 脚本中,我尝试使用两个日期时间参数调用另一个脚本。

父脚本:

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

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

子脚本:

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

$startDate| Write-Output

结果:

2015 年 2 月 10 日,星期二 00:00:00

-> 时间浪费了!

有人知道为什么吗?

问题是您正在使用字符串调用脚本

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

$startdate$enddate 包含日期和时间之间的空格,因此在解析时,日期被视为参数的值,但由于空格,时间被视为一个论点。下面的示例显示了这一点。

test1.ps1:

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

$startDate| Write-Output

"Args:"
$args

脚本:

$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"

输出:

#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

这里有两种解决方法。您可以直接 运行 脚本而无需 Invoke-Expression,它会正确发送对象。

c:\test.ps1 -startDate $startDate -endDate $endDate

输出:

c:\test.ps1 -startDate 02/05/2015 19:00 -endDate 02/06/2015 14:15

5. februar 2015 19:00:00

或者您可以在表达式字符串中引用 $startDate$endDate,例如:

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

或者试试这个:

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