Reputation: 21
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)
}
Upvotes: 1
Views: 366
Reputation: 61263
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
Upvotes: 2
Reputation: 72680
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".
Upvotes: 1