Powershell v2.0 替换散列中的空值 table
Powershell v2.0 substitute null values from a Hash table
我有一个散列 table 如下:
$Hash = @{
Team1=$Team1.count
Team2=$Team2.count
Team3=$Team3.count
}
$GroupByTeam = New-Object psobject -Property $Hash |
Select 'Team1','Team2','Team3' | ConvertTo-Html -Fragment
这很好,每个 "team" returns 都有自己的价值。但是,团队可能有一个空值,我希望用它代替“0”。
为了解决这个问题,我尝试先 select 空值,但似乎无法做到这一点:
$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}
有什么想法吗?
感谢
您要做的是收集引用空值的 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 }
您最好的选择是在创建哈希表时将值转换为 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 }
}
或(如 建议)使用 Keys
属性 到同一端:
($Hash.Keys) | ForEach-Object {
if ($Hash[$_] -eq $null) { $Hash[$_] = 0 }
}
请注意,无论哪种方式,您都需要使用子表达式(或将枚举的 objects/keys 分配给变量),否则您会收到错误消息,因为您在枚举数据结构时正在修改它。
我有一个散列 table 如下:
$Hash = @{
Team1=$Team1.count
Team2=$Team2.count
Team3=$Team3.count
}
$GroupByTeam = New-Object psobject -Property $Hash |
Select 'Team1','Team2','Team3' | ConvertTo-Html -Fragment
这很好,每个 "team" returns 都有自己的价值。但是,团队可能有一个空值,我希望用它代替“0”。
为了解决这个问题,我尝试先 select 空值,但似乎无法做到这一点:
$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}
有什么想法吗?
感谢
您要做的是收集引用空值的 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 }
您最好的选择是在创建哈希表时将值转换为 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 }
}
或(如 Keys
属性 到同一端:
($Hash.Keys) | ForEach-Object {
if ($Hash[$_] -eq $null) { $Hash[$_] = 0 }
}
请注意,无论哪种方式,您都需要使用子表达式(或将枚举的 objects/keys 分配给变量),否则您会收到错误消息,因为您在枚举数据结构时正在修改它。