我有一个哈希表如下:
$Hash = @{
Team1=$Team1.count
Team2=$Team2.count
Team3=$Team3.count
}
$GroupByTeam = New-Object psobject -Property $Hash |
Select 'Team1','Team2','Team3' | ConvertTo-Html -Fragment
这很好,每个“团队”都会返回自己的价值。但是,团队可能具有空值,我希望将其替换为“0”。
为了解决这个问题,我尝试先选择空值,但似乎无法做到这一点:
$Hash.values | select -property Values
Values
------
{1, 2}
但是
$Hash.values | select -property Values | where {$_.Values is $null}
不会退回任何东西。还尝试过:
$Hash.values | select -expandproperty Values | where {$_.Values is $null}
有什么想法吗?
谢谢
答案 0 :(得分:2)
您要做的是收集引用空值的keys
,然后使用0
s填充那些:
# Create and populate hashtable
$HashTable = @{
Team1 = 123
Team2 = $null
Team3 = 456
}
# Find keys of `$null` values
$nullKeys = $HashTable.Keys |Where-Object { $HashTable[$_] -eq $null }
# Populate appropriate indices with 0
$nullKeys |ForEach-Object { $HashTable[$_] = 0 }
答案 1 :(得分:2)
您最好的选择是在创建哈希表时将值转换为int
:
$Hash = @{
Team1 = [int]$Team1.Count
Team2 = [int]$Team2.Count
Team3 = [int]$Team3.Count
}
如果由于某种原因这是不可能的,你可以选择一个普查员:
($Hash.GetEnumerator()) | ForEach-Object {
if ($_.Value -eq $null) { $Hash[$_.Name] = 0 }
}
或(建议使用Mathias)将Keys
属性用于同一目的:
($Hash.Keys) | ForEach-Object {
if ($Hash[$_] -eq $null) { $Hash[$_] = 0 }
}
请注意,您需要使用子表达式(或将枚举的对象/键指定给变量),否则您将收到错被列举。