help understanding this code

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Shane Lindberg Shane Lindberg 1 year, 8 months ago.

  • Author
    Posts
  • #31772
    Profile photo of Shane Lindberg
    Shane Lindberg
    Participant

    I was trying to read this code from this link
    http://stackoverflow.com/questions/14527832/powershell-how-to-invoke-a-checkbox-windows-with-multiple-choice

    in particular this part of the code

    $handler_button1_Click= 
    {
        $listBox1.Items.Clear();    
    
        if ($checkBox1.Checked)     {  $listBox1.Items.Add( "Checkbox 1 is checked"  ) }
    
        if ($checkBox2.Checked)    {  $listBox1.Items.Add( "Checkbox 2 is checked"  ) }
    
        if ($checkBox3.Checked)    {  $listBox1.Items.Add( "Checkbox 3 is checked"  ) }
    
        if ( !$checkBox1.Checked -and !$checkBox2.Checked -and !$checkBox3.Checked ) {   $listBox1.Items.Add("No CheckBox selected....")} 
    }
    
    $OnLoadForm_StateCorrection=
    {#Correct the initial state of the form to prevent the .Net maximized form issue
        $form1.WindowState = $InitialFormWindowState
    }
    

    both of these lines below seem to be trying set a variable to items in brakets. What is going on there in a general sense, not specifically about the form.
    $handler_button1_Click=
    $OnLoadForm_StateCorrection=

  • #31773
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    The code in the brackets are simply an object of type ScriptBlock. In this case, they're assigning those script block objects to variables, presumably to assign them as event handlers later ($button1.add_Click($handler_button1_Click), etc).

  • #31774
    Profile photo of Shane Lindberg
    Shane Lindberg
    Participant

    forgive my basic quesitons and lack of genral understanding. When I do

    $a=
    {#Correct the initial state of the form to prevent the .Net maximized form issue
    'hhh'
    }
    
    Write-Host $a
    

    I get this output
    #Correct the initial state of the form to prevent the .Net maximized form issue
    'hhh'

    Why is the comment is the code above not part of the variable like my example here?

  • #31775
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    The comment is part of the script block, though it gets ignored when you actually execute that block.

    Are you not seeing the comment as part of the Write-Host output? I do see it, but I'm running the PowerShell v5 production preview, and maybe this is something they fixed along the way.

  • #31776
    Profile photo of Shane Lindberg
    Shane Lindberg
    Participant

    I get it it. I can be a bit dense sometimes 🙂 Thanks!

You must be logged in to reply to this topic.