2015-03-31 47 views
1

嗨我得到这个格式错误,当我尝试并指定一个DateTime参数的值。这里是我的脚本这我在PowerShell ISE中按F5运行:

param 
(
    [Parameter(Mandatory=$true)] 
    [datetime]$startTime 
) 

write-output $startTime 

当我运行它,它说,这Supply values for the following parameters:。我曾尝试指定以下:

startTime: get-date 
startTime: (get-date) 
startTime: new-object DateTime(2015,03,31) 
startTime: (new-object DateTime(2015,03,31)) 
startTime: $(get-date) 
startTime: $((get-date)) 
startTime: $(new-object DateTime(2015,03,31)) 
startTime: $((new-object DateTime(2015,03,31))) 

不过,我不断收到此错误:

Cannot recognise $startTime as a system.datetime due to a format error 

UPDATE: 原来你需要指定类似3/31/2015。 这是为什么?上述DateTime对象的格式有什么问题?

+1

你有没有尝试过像'3/31/2015'这样简单的参数输入? – TheMadTechnician 2015-03-31 03:23:43

+0

这有效! 但是为什么?我以错误的格式提供的论点如何? – 2015-03-31 03:26:24

回答

2

我不能完全重复你所看到的。这里是我的脚本:

7> Get-Content .\startTime.ps1 
param 
(
    [Parameter(Mandatory=$true)] 
    [datetime]$startTime 
) 

write-output $startTime 

调用像这样工作的:

8> .\startTime.ps1 (Get-Date) 

Monday, March 30, 2015 9:48:01 PM 

BTW .\startTime.ps1 get-date不起作用,因为该参数值是字面上的字符串get-date不能被强制转换为DateTime对象。同上,用于.\startTime.ps1 new-object DateTime(2015,03,31)因为开始时间得到的文本字符串new-object,但这样做的工作:

10> .\startTime.ps1 (new-object DateTime 2015,03,31) 

Tuesday, March 31, 2015 12:00:00 AM 

子表达式版本应该工作以及:

11> .\startTime.ps1 $(new-object DateTime 2015,03,31) 

Tuesday, March 31, 2015 12:00:00 AM 

BTW .\startTime.ps1 3/31/2015作品,因为文本字符串3/31/2015可以强制转换一个DateTime对象。

更新:啊,你正在使用ISE的强制参数提示功能。我之前遇到过这个问题。此处提供的值仅作为字符串应用,即不会评估表达式或子表达式。

+0

不要调用脚本,只需在Powershell ISE中打开脚本并单击播放按钮即可。 – 2015-03-31 03:55:38

+1

啊,你正在使用ISE的强制参数提示功能。我之前遇到过这个问题。此处提供的值仅作为字符串应用,即不会评估表达式或子表达式。 – 2015-03-31 04:55:41

+0

我想这就是答案,但我不能将它标记为答案,因为您将它写为评论。 – 2015-03-31 05:21:16

相关问题