Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through an array of objects in Powershell

Tags:

powershell

I'm doing some basic validation on form fields. What's the correct way to iterate through an array of objects to validate them? When I try the below I get

The property 'BackColor' cannot be found on this object. Verify that the property exists and can be set.

I guess what I'm missing is a way of telling Powershell these are references to other variables, rather than variables themselves.

$MandatoryFields = @(
    'txtUsername',
    'txtFirst',
    'txtLast',
    'txtEmail',
    'ComboLicense'
)

ForEach ($Field in $MandatoryFields) {
    If ([string]::IsNullOrWhitespace($Field.text)) {
        $Validation = "failed"
        $Field.BackColor = "red"
    }
}

EDIT: Okay, what I needed was the actual variables in the array, like so:

$MandatoryFields = @(
    $txtUsername,
    $txtFirst,
    $txtLast,
    $txtEmail,
    $ComboLicense
)
like image 612
daninthemix Avatar asked Oct 14 '25 16:10

daninthemix


1 Answers

Try adding your objects to an array like below

$objects = [System.Collections.ArrayList]@()

$myObject = [PSCustomObject]@{
    Name     = 'Kevin'
    Language = 'PowerShell'
    State    = 'Texas'
}


$objects.add($myObject)

$myObject1= [PSCustomObject]@{
    Name     = 'Kevin'
    Language = 'PowerShell'
    State    = 'Texas'
}


  $objects.add($myObject1)

foreach($obj in $objects){

$obj.firstname

}
like image 154
TheGameiswar Avatar answered Oct 17 '25 11:10

TheGameiswar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!