locked
Reference the value of function called in a foreach loop RRS feed

  • Question

  • I have a form with two list boxes in it.  The first list box is populated with a list of server names.  When I click on a server name, I want it to populate the second list box with the list of services it finds on that server.  I have a function that queries the server for it's services:

    Function GetServicesList([STRING]$ServerName)
    {
     Return Get-Service -ComputerName $ServerName | Select-Object Name | Sort-Object Name
    }

    Then in my form I am trying this, but I am not sure how to reference the value that is returned from the function:

    $objListBoxServers = New-Object System.Windows.Forms.ListBox
    $objListBoxServers.Location = New-Object System.Drawing.Size (15,40)
    $objListBoxServers.Size = New-Object System.Drawing.Size (260,140)
    $objListBoxServers.TabIndex = 0
    $objListBoxServers.add_SelectedValueChanged({ForEach ($Service in GetServicesList($objListBoxServers.SelectedItem)){$objListBoxSerivces.Items.Add($_)}})
    $objForm.Controls.Add($objListBoxServers)

    Thus, when an item (a server name) is clicked, I am assuming it fires off the "add_SelectedValueChanged" event and then runs the code "({ForEach ($Service in GetServicesList($objListBoxServers.SelectedItem)){$objListBoxSerivces.Items.Add($_)}}"

    I am getting stuck on the {$objListBoxSerivces.Items.Add($_)} - the Add($_) is not working.  The $_ feature has always confused me - I have used it in the past but just gotten lucky without really understanding why/how it works.  In this case it is not working.  When do you use $_. and when do you use $_ etc.

    Can anyone point me in the right direction on what I should be using and also provide a brief tutorial on the $_ convention and when it can/should be used.

    thanks,

    NK


    • Edited by NJK-Work Tuesday, December 17, 2013 3:19 PM
    Tuesday, December 17, 2013 3:18 PM

Answers

  • Oh duh - boy do I feel stupid.

    I had several syntax errors in my code and a typo in an object name.  And then I realized I needed to simply reference "$Service":

    $objListBoxServers.add_SelectedValueChanged({ForEach ($Service in (GetServicesList $objListBoxServers.SelectedItem)){$objListBoxServices.Items.Add($Service.Name)}})



    • Marked as answer by NJK-Work Tuesday, December 17, 2013 4:10 PM
    • Edited by NJK-Work Tuesday, December 17, 2013 4:11 PM
    Tuesday, December 17, 2013 4:10 PM