Powershell While循环用户输入
从新方法开始提出新问题。 这里的旧线程: 所以我有一个参数用于定义日期,它的格式必须是yyyy-mm-dd 如果格式不正确,无法验证为datetime或null,我希望它继续询问,因此我们认为while循环可以工作,但无法确定如何完成Powershell While循环用户输入,powershell,parameters,while-loop,Powershell,Parameters,While Loop,从新方法开始提出新问题。 这里的旧线程: 所以我有一个参数用于定义日期,它的格式必须是yyyy-mm-dd 如果格式不正确,无法验证为datetime或null,我希望它继续询问,因此我们认为while循环可以工作,但无法确定如何完成 Param ( [parameter(mandatory=$false)][alias('d')][string]$date #date in format yyyy-mm-dd ) if ($da
Param (
[parameter(mandatory=$false)][alias('d')][string]$date #date in format yyyy-mm-dd
)
if ($date){
try {get-date($date)}
catch{
While($date -ne $null){
Write-host "The Date is invalid and need to be in this format, yyyy-mm-dd" -ForeGroundColor Yellow
$date = read-host
clear
}
}
}
这种方法是可行的,但当格式正确时,它最终会变成一个无限循环
Param (
[parameter(mandatory=$false)][alias('d')][string]$date #date in format yyyy-mm-dd
)
if ($date){
do{
try {get-date($date)}
catch{
clear
Write-host "The Date is invalid and need to be in this format, yyyy-mm-dd" -ForeGroundColor Yellow
$date=read-host
}
}
until($date -eq $('^\d{4}-\d{2}-\d{2}$'))
}
您可以使用以下功能:
param (
[parameter(mandatory=$false)][alias('d')][string]$date #date in format yyyy-mm-dd
)
function IsParsable() { try { get-date($date) } catch { return $false }; return $true }
while (-not (IsParsable))
{
clear
Write-host "The Date is invalid and need to be in this format, yyyy-mm-dd" -ForeGroundColor Yellow
$date = read-host
}
# do whatever you want with $date here
为什么不直接将参数指定为type
[DateTime]
?虽然我完全同意Bill_Stewart的[DateTime]
建议是最好的解决方案,但另一种方法是使用[ValidatePattern('^\d{4}-\d{2}-\d{2}$')
@BenH,如果你看一下我最初的问题线程,我从使用Datetime和validatepattern进行验证开始。但是因为我想要一个自定义错误,所以我最终得到了这个解决方案。如果您确实设置了参数[DateTime]$date,则如果您输入任何数字,它将继续。转换为[DateTime]
和验证时会出现不同的错误ParameterArgumentTransformationError
vsParameterArgumentValidationError
@Bill_Stewart“Param([parameter(mandatory=$false)][alias('d')][Datetime]$date)”将接受任何数字