2017-07-26 4 views
0

私はユーザーの入力に基づいて結果を取得するためのスクリプトを書いています、ここでユーザーは日付または日付の時間を与えることができます...私は入力に基づいて結果を取得する必要があります日付時刻)。powershellの日付の異なる方法を入力

$StartDate = Read-Host -Prompt 'Enter the start date of the logs, Ex: 17/07/2017 or 17/07/2017 09:00:00' 

$culture = [Globalization.CultureInfo]::InvariantCulture 

$pattern = 'dd\/MM\/yyyy HH:mm:ss', 'dd\/MM\/yyyy' 

$params['After'] = [DateTime]::ParseExact($StartDate, $pattern, $culture) 

以下のエラー取得:私は以下のように試してみました

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime." 
+  $params['After'] = [DateTime]::ParseExact <<<< ($StartDate, $pattern, $culture) 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : DotNetMethodException 

を提案してくださいは、私はここで何をしないのです。

答えて

3

PowerShellのデフォルトのGet-Date関数を日付に使用して幸運を祈っています。私は次のように使用してみます:あなたはまだParseExact()を使用したい場合は

$StartDate = Get-Date (Read-Host -Prompt 'Enter the start date of the logs, Ex: 17/07/2017 or 17/07/2017 09:00:00') 
0

、あなたの問題は$patternは、文字列の配列ではなく、文字列のことでした。どのパターンを使用するかを確認し、そのパターンだけを渡すことができます。

$StartDate = Read-Host -Prompt 'Enter the start date of the logs, Ex: 17/07/2017 or 17/07/2017 09:00:00' 

$culture = [Globalization.CultureInfo]::InvariantCulture 

if ($startdate -match '^\w\w\/\w\w\/\w\w\w\w$') { 
    $pattern = 'dd\/MM\/yyyy' 
} else { 
    $pattern = 'dd\/MM\/yyyy HH:mm:ss' 
} 

$params['After'] = [DateTime]::ParseExact($StartDate, $pattern, $culture) 
0

私はおそらくちょうど短い機能を使用します。以下のようなもの:

function Read-Date { 
    param(
    [String] $prompt 
) 
    $result = $null 
    do { 
    $s = Read-Host $prompt 
    if ($s) { 
     try { 
     $result = Get-Date $s 
     break 
     } 
     catch [Management.Automation.PSInvalidCastException] { 
     Write-Host "Date not valid" 
     } 
    } 
    else { 
     break 
    } 
    } 
    while ($true) 
    $result 
} 

は、その後、あなたはこれを書くことができます。ユーザーが有効な日付のような文字列を入力するまで

Read-Date "Enter a date" 

コードが要求されます。ユーザーが有効な日付文字列を入力すると、関数の出力は[DateTime]オブジェクトになります。

関連する問題