创建Powershell脚本以增强用户输入



付款行的呼叫者输入4位到期日MMYY,但我需要确保这是未来的有效日期。

我已经尝试过获取日期,但在检查获取日期Uformat MMyy之前,我需要确保4位数字转换为日期格式。

任何帮助都将是伟大的

感谢

使用[DateTime]::ParseExact

$monthYear = "0524"
try {
if ([DateTime]::ParseExact($monthYear,'MMyy', $null) -gt $(get-date)) {
Write-Output "valid date in the future" 
} else {
Write-Output "valid date in the past"
}
}
catch {
Write-Output "invalid date"
}

更改$monthYear以验证行为。

$read = read-host enter date in the future in format MMYY
try{
$month = [int]($read[0..1] -join "")
$year = [int]($read[2..3] -join "")
$date = get-date -Month $month -Year "20$year"
if(((get-date) - $date) -le 0){
write-host "You have entered a valid date in the future: $date" -ForegroundColor Green
}else{
Write-Error Not a valid Date 
}
}catch{
write-host you have entered an invalid date -ForegroundColor Red
}

这是我使用[DateTime]::TryParseExact():的两个元素

$mmyy = "0524"   # user input
$checkDate = (Get-Date).Date
$thisMonth = (Get-Date -Year $checkDate.Year -Month $checkDate.Month -Day 1).Date
if ([DateTime]::TryParseExact($mmyy, 'MMyy', $null, 'None', [ref]$checkDate)) {
# [math]::Sign() returns -1 for a negative value, +1 for a positive value or 0 if the value is 0 
switch ([math]::Sign(($checkDate - $thisMonth).Ticks)) {
-1 { "$checkDate is in the past" }
1 { "$checkDate is in the future" }
default {  "$checkDate is this month" }
}
}
else {
write-host "Invalid date" -ForegroundColor Red
}

最新更新