2016-11-09 41 views
1

我在PowerShell中的哈希表看起來像這樣($hash_dates.GetEnumerator() | sort -Property name):循環遍歷哈希表中的日期?

11/1/2016 12:00:00 AM   5 
11/2/2016 12:00:00 AM   3 
11/4/2016 12:00:00 AM   2 

的關鍵是DateTime類型。

我正在運行一個for循環來捕獲所有日期(僅限日期,因此所有午夜都不重要),並根據日期提取散列表中的每個值。代碼:

$startdate = (get-date).AddDays(-30) 
$today = get-date -format G 
for($i = $startdate; $i -lt $today; $i=$i.AddDays(1)) 
{ 
    $z = $i -split " " 
    $z = [datetime]$z[0] 
    $z = Get-Date $z -format G 
    "Comparing $z to: " 
    $hash_dates.Keys | ? { $hash_dates[$_] -eq $z } 
} 

我用-format Gsplit,以保證格式匹配。但循環從未找到任何結果(即使它通過11/1/2016等循環)。我錯過了什麼嗎?

+2

'$ today'是一個字符串。 '$ i -lt $ today'沒有意義 –

+0

@ MathiasR.Jessen嗯。但循環工作得很好。它從今天開始30,並循環到今天,並輸出「比較:」每個過程。它只是沒有找到任何散列鍵。 – Zeno

+0

@Zeno:'$ i -lt $ today'按預期工作的唯一原因是_string_'$ today'被重新轉換爲'[datetime]'_作爲比較_,因爲_LHS_的類型是'[datetime]' ,但沒有很好的理由將'$ today'表示爲一個字符串。 – mklement0

回答

3

由於您哈希表鍵[datetime]對象,有沒有必要使用日期字符串和字符串解析都:

$today = (Get-Date).Date # Note the .Date part, which omits the time portion 
$startdate = $today.AddDays(-30) 

# Note the change from -lt to -le to include today 
for($i = $startdate; $i -le $today; $i = $i.AddDays(1)) 
{ 
    # Note that `echo` is an alias for `Write-Output`, which is the default, 
    # so no need for an explicit output command. 
    "Looking for $i..." 
    # Simply try to access the hashtable with $i as the key, which 
    # either outputs nothing ($null), or outputs the value for that key. 
    $hash_dates.$i 
} 

重新echo/Write-Output /默認的輸出:請注意,您的狀態消息將成爲您的數據(輸出)流,這可能是不希望的。
請考慮使用Write-Information


這裏有一個簡化的解決方案演示PowerShell中的表現:

$today = (get-date).Date 

# Construct an array with all dates of interest. 
$dates = -30..0 | % { $today.AddDays($_) } # % is a built-in alias for ForEach-Object 

# Pass the entire array as the hashtable "subscript", which returns 
# the values for all matching keys while ignoring keys that don't exist. 
$hash_dates[$dates] 
0

這是你想要的嗎?

$startdate = (get-date).AddDays(-30) 
$today = get-date -format G 
for($i = $startdate; $i -lt $today; $i=$i.AddDays(1)) 
{ 
    $z = $i -split " " 
    $z = [datetime]$z[0] 
    Echo "Comparing $z to: " 
    $z = Get-Date $z 
    $hash_dates.$z 

} 
+0

通過鍵('$ hash_dates。$ z')訪問散列表以檢索值是正確方向的一個步驟, 您的答案不能解決所有不必要和脆弱的日期到字符串轉換和解析。 – mklement0