在我的脚本中,我有一个日期参数,它需要以特定的格式,我已经用validatescript和regex解决了这个问题。这很好,但我想要一个自定义错误,如果a.您的日期不验证为DateTime b.您的日期不验证正则表达式
Param (
[parameter(mandatory=$false)]
[ValidateScript({
If ($_ -match "^([0-9]{4}[-]?((0[13-9]|1[012])[-]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-]?31|02[-]?(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00)[-]?02[-]?29)") {
$True
}
else {
Write-host "The Date is invalid and need to be in this format, 2017-07-25" -ForeGroundColor Yellow
}
})]
[datetime]$date
)正在思考着用尝试和捕捉
[ValidateScript({
try {
$_ -notmatch "^([0-9]{4}[-]?((0[13-9]|1[012])[-]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-]?31|02[-]?(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00)[-]?02[-]?29)"
} catch [System.Management.Automation.ParameterBindingValidationException] {
Write-host "The Date is invalid and need to be in this format, 2017-07-25" -ForeGroundColor Yellow
}
)]有什么建议吗?
编辑:
改为:
Param (
[parameter(mandatory=$false)][alias('d')][string]$date #date in format yyyy-mm-dd
)
if ($date){
try {get-date($date)}
catch{
Write-host "The Date is invalid and need to be in this format, yyyy-mm-dd" -ForeGroundColor Yellow
$date = getdate(read-host)
}
}工作,但如果不遵守所要求的格式,然后继续输入,例如再次键入070725,您将得到一个错误。有什么方法循环它直到你得到正确的格式吗?或者做个直到循环?
发布于 2017-07-25 09:39:32
我想你可能走错路了?
为什么不让用户输入他想要的东西呢?检查输入的内容是否验证为System.DateTime。然后使用$date.ToString(“yyyy”)按您想要的方式对其进行格式化,并对其进行regex检查(如果有必要的话)。
在我看来,更好的做法是使用DateTime对象上的属性进行验证,而不是重新定义字符串。
(很抱歉将此作为回复,这是一个更多的评论,但我不能这样做)
发布于 2017-07-25 13:10:10
TL;博士-与datetime 或 string匹配,而不是两者都匹配。
我不理解同时拥有一个datetime和一个特定格式的datetime的要求。
或者您有一个datetime对象,它在显示为字符串时使用与区域性相关的设置。或者使用ToString()显式地获取您想要的格式(例如,.ToString("yyyy-MM-dd"))。
或者您有一个String对象,它具有特定的字符串形式。但不能将其视为日期,因此可以使用.ToDateTime()或其他方法将其转换为datetime对象。
这种治疗也会在ValidateScript中引起问题。
$date是一个有效的datetime- In which case it is successfully cast as `datetime` before the `ValidateScript` is called. And `ToString()`) will need to be used before you can run rrgex on it.
datetime- In which case it is unsuccessfully cast as `datetime`, and a PowerShell error is thrown. Before the `ValidateScipt` can run and through your custom error.
字符串
Param (
[parameter(mandatory=$false)]
[ValidateScript({
try{
$culture = [cultureinfo]::InvariantCulture
[datetime]::ParseExact($_,"yyyy-MM-dd",$culture)
}catch{
throw "The Date is invalid and need to be in this format, 2017-07-25"
}
})
]
[string]$date
)
Write-Host $date
Write-Host $date.GetType()
# if you actually want a datetime object
$date = [datetime]::ParseExact($date,"yyyy-MM-dd",$culture)Datetime
[CmdletBinding()]
Param (
[parameter(mandatory=$false)]
[datetime]$date
)https://stackoverflow.com/questions/45298777
复制相似问题