Search code examples
powershell

Validate each value in PSCustomObject - Powershell


I'm having a bit of trouble making something that may be rather easy to make but I'm not finding the path.

I'm trying to make a verifier PSCustomObject to validate multiple input from the whole program so at the end it enables a button (has wpf interface).

Right now I'm using an IF statement with multiple conditions (one for each property in the verifier object) to check if all verifications are true, but is taking quite the length in the script.

Here's an example of what I have now:

PSCustomObject]$verifier = @{
  'Item1' = $false
  'Item2' = $false
  'Item3' = $false
  'Item4' = $false
  'Item5' = $false
}

Code where users modifies the input that alters the items in the pscustomobject:

if(($verifier.Item1) -and ($verifier.Item2) -and ($verifier.Item3) -and ($verifier.Item4) -and ($verifier.Item5)){
  *enable the button*
}
else{
  *graphically show the user the wrong/missing input*
}

Is there any way to make that IF statement simpler? Tried using foreach but it's verifying all values at the same time instead of evaluating each one.

I want the condition to return true when all are true and false when any number of values are false, and recover those that are false.

Thanks in advance for the help!


Solution

  • Is there any way to make that IF statement simpler?

    Definitely, use a containment operator:

    $verifier = [PSCustomObject]@{
        'Item1' = $true
        'Item2' = $true
        'Item3' = $true
        'Item4' = $true
        'Item5' = $true
    }
    
    if($verifier.PSObject.Properties.Value -notcontains $false) {
        'enable the button'
    }
    else {
        'graphically show the user the wrong/missing input'
    }
    

    You can access the values of all properties via PSObject intrinsic member.


    Note: There is a clear distinction between $verifier = [PSCustomObject]@{ and [PSCustomObject] $verifier = @{, the former will return a custom object while the latter is only constraining the variable but will not convert that hash table to a custom object. The [pscustomobject] type accelerator only works when casting it from a dictionary.

    If you want to use a hashtable instead of a PSCustomObject, then call the .Values property from it:

    $verifier = @{
        'Item1' = $true
        'Item2' = $true
        'Item3' = $true
        'Item4' = $true
        'Item5' = $true
    }
    
    if($verifier.Values -notcontains $false) {
        'enable the button'
    }
    else {
        'graphically show the user the wrong/missing input'
    }