0

How do I check for empty values in an hashtable, and list the item name as well ?

I could do if ($Vars.ContainsValue($null)) but this does not get me what item that has a $null value

    $Vars = @{

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

} 

if I do a foreach ($var in $vars) I get the whole hashtable?

1 Answer 1

2

First of all this is not an array, because those are written as @('element1', 'element2'). This concerns a HashTable which is indicated as @{} and is enumerated by the GetEnumerator() method.

After that method it's simply a matter of filtering out what you need with the key and/or the value property.

$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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nicely done. The following is worth mentioning in general (not a concern with the given data): -not $_.Value would also exclude other values, such as 0, $false, or an empty array. Also, arrays are best written as 'element1', 'element2' - the @(...) is not only unnecessary, it is actually less efficient in PowerShell 5.0 and below (though it won't matter in practice). @(...) is useful for constructing an empty array or a single-element array, though (the latter can also be constructed as , <elem>).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.