如何在一行中输入用户的日期和时间

时间:2012-10-25 18:31:09

标签: powershell powershell-v2.0

如何将以下所有内容放入一行,以便用户能够立即进入?

所以,每当他们想要输入内容时,不会弹出Read-Host - 它会弹出一次并说明你想要输入日期的内容......

所以 - “请随时间输入完整日期 - 即2012年10月25日9:00”

此外 - 如果有人输入一个奇怪的角色,我怎么能让它出错呢?

$Day = $(Read-Host "Enter day of month")
if ($Day -eq ''){$Day = Get-Date -format dd}

$Month = $(Read-Host "Enter Month of Year")
if ($Month -eq ""){$Month = Get-Date -format MM}

$Year = $(Read-Host "Enter Year")
if ($Year -eq "") {$Year = Get-Date -format yy}

$Hour = $(Read-Host "Enter Hour")
if ($Hour -eq "") {$Hour = Get-Date -Format HH}

$Minute = $(Read-Host "Enter Minute")
if ($Minute -eq "") {$Minute = Get-Date -Format mm}

$Second = $(Read-Host "Enter Hour")
if ($Second -eq "") {$Second = Get-Date -Format ss}

1 个答案:

答案 0 :(得分:4)

您可以这样做:

do
{
    $date= read-host "Please enter date & time (i.e.: '25/12/2012 09:00', '25 oct 2012 9:00'; date alone set time to 00:00):"

    $date = $date -as [datetime]

    if (!$date) {
        "Not A valid date and time"
    }
} while ($date -isnot [datetime])

$date