的問題是,您使用的是串
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」。它只是非常少需要的(與eval'相同,在很多其他語言中,它實際上是這樣)。它只會使事情複雜化,拋棄PowerShell所帶來的每一個好處,而且幾乎不會解決問題(只是另一個問題)。 – Joey 2015-02-11 07:47:35