[英]Pass Datetime to powershell script
In a powershell script, I try to call another script with two datetime parameters. 在Powershell脚本中,我尝试使用两个datetime参数调用另一个脚本。
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 2015年2月10日,星期二, 00:00:00
-> The time is lost ! ->时间浪费了!
Does anybody know why ? 有人知道为什么吗?
The problem is that you're calling the script using a string 问题是您正在使用字符串调用脚本
Invoke-Expression
"C:\\MoveAndDeleteFolder.ps1 -startDate $startDate -endDate $endDate"
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. $startdate
和$enddate
在日期和时间之间包含一个空格,因此在对其进行解析时,日期被视为参数的值,但由于存在空格,因此将时间视为参数。 The sample below shows this. 下面的示例显示了这一点。
test1.ps1: 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. 您可以直接运行脚本而无需
Invoke-Expression
,它将正确发送对象。
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: 或者,您可以在表达式字符串中引用
$startDate
和$endDate
,例如:
Invoke-Expression "C:\MoveAndDeleteFolder.ps1 -startDate '$startDate' -endDate '$endDate'"
或尝试以下方法:
Invoke-Expression "C:\MoveAndDeleteFolder.ps1 -startDate `"$startDate`" -endDate `"$endDate`""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.