Search code examples
arrayspowershellhashtable

Check for empty value in Array


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?


Solution

  • 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
    }