1

I am unable to access my object using .PropertyName.

I have tried using $val.Options.$propertyName but it yields no result.

$propertyName is a value input from a file

`$val.$propertyName` results in "Cannot index into null array"

$result = New-Object -TypeName 'System.Collections.ArrayList';
        foreach ($user in $users) {
            $val = Get-LocalUser $user | Select *
            $val = $val.$propertyName
            $result.Add($val)
        }
1
  • 2
    In addition to JPBlanc's answer, note that there is no performance advantage of adding to an ArrayList vs just doing $result = foreach ($user in $users) { Get-LocalUser $user | Select * } Commented Aug 4, 2021 at 18:48

2 Answers 2

2

You don't need an arraylist at all. Just let PowerShell do the collecting by capturing the output inside the loop

$result = foreach ($user in $users) {
    (Get-LocalUser $user).$propertyName
}
This is assuming your variable `$propertyName` contains a valid attribute name

While the above code does what you've asked for, I don't think the result would be very helpful, because it just lists whatever is in the property stored in $propertyName, and you cannot see which user has what values in there. A better approach would be to output objects with the properties you want returned.

Something like

# just an example..
$propertyName = 'Description'
$users        = 'WDAGUtilityAccount', 'Administrator'
$result = foreach ($user in $users) {
    output an object with the name of the user, and also the property you are after
    Get-LocalUser $user | Select-Object Name, $propertyName
}

$result

Since parameter -Name (the first positional parameter) can take an array of usernames, this can be shortened to:

$result = Get-LocalUser $users | Select-Object Name, $propertyName
Sign up to request clarification or add additional context in comments.

Comments

1

In your context $val.$propertyName does't mean anything can you try :

$result = New-Object -TypeName 'System.Collections.ArrayList';
        foreach ($user in $users) {
            $val = Get-LocalUser $user
            $result.Add($val)
        }

$result will be an array of "Localuser".

Comments

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.