help understanding this code

Welcome Forums General PowerShell Q&A help understanding this code

This topic contains 4 replies, has 2 voices, and was last updated by

 
Participant
3 years ago.

  • Author
    Posts
  • #31772

    Participant
    Points: 1
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 1
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 1
    Rank: Member

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

The topic ‘help understanding this code’ is closed to new replies.