检查数组中的空值

时间:2019-10-21 12:53:36

标签: arrays powershell hashtable

如何检查哈希表中的空值,并列出项目名称?

我可以做if ($Vars.ContainsValue($null)),但这不能让我知道哪个商品具有$null

    $Vars = @{

    1     = "CustomerID";
    2     = "DepartmentID";
    3     = "Environment";
    4     = "JoinDomain";
    5     = ""

} 

如果我做foreach ($var in $vars),我会得到整个哈希表?

1 个答案:

答案 0 :(得分:2)

首先,这不是array,因为它们被写为@('element1', 'element2')。这涉及到HashTable,它表示为@{},并由enumerated方法表示为GetEnumerator()

使用该方法之后,只需使用key和/或value属性过滤掉所需的内容即可。

$Vars = @{
    1 = "CustomerID";
    2 = "DepartmentID";
    3 = "Environment";
    4 = "JoinDomain";
    5 = ""
}

$VerbosePreference = 'Continue'

$Vars.GetEnumerator() | Where-Object {
    -not $_.Value
} | ForEach-Object {
    Write-Verbose "The key '$($_.Key)' has no value"
    # Other code for handling the key with no value
}