Author Posts

May 22, 2017 at 7:01 pm

I'm having an issue trying to create some dynamic variables as I am needed to create multiple ListViewItems depending on how many items return in a search result. Here is what I have...

$disUsers is actually what the user will type in but using hardcoded for testing purposes

$disUsers = "chad*"
$names = Get-ADUser -Filter {name -like $disUsers} | Select -ExpandProperty name
$i=0
foreach ($name in $names) {
$namevar = New-Object System.Windows.Forms.ListViewItem("$names")
New-Variable -Name "listnames$i" -value $namevar
$i++
}

However, when calling $listname[1] or whatever number there is nothing there. When just doing $names I get all the AD account names. I'll need to eventually, dynamically also add every ListViewItem into

$UserList.Items.AddRange(($listnames))

But I'll get to that hurdle when I get there.

May 22, 2017 at 7:07 pm

$names = Get-ADUser -Filter {name -like $disUsers} | Select -ExpandProperty name
$i=0
foreach ($name in $names) {
$namevar = New-Object System.Windows.Forms.ListViewItem($names[$i])
New-Variable -Name "listnames$i" -value $namevar
$i++
}

Needed to change $namevar = New-Object System.Windows.Forms.ListViewItem("$names") to $names[$i]

May 22, 2017 at 8:55 pm

May I suggest a simpler approach:

$disUsers = "chad*"
$Names = Get-ADUser -Filter {name -like $disUsers} | Select -ExpandProperty name
$ListViews = $Names | % { New-Object System.Windows.Forms.ListViewItem($_) }
$ListViews