Dynamic Variables

This topic contains 2 replies, has 2 voices, and was last updated by  Sam Boutros 6 months ago.

  • Author
    Posts
  • #71239

    Chad Nathan Jones
    Participant

    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.

  • #71240

    Chad Nathan Jones
    Participant
    $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]

  • #71251

    Sam Boutros
    Participant

    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
    

You must be logged in to reply to this topic.