0

I am trying to create a function which will return various form objects. eg Label. However I am not able to achieve the same.

My code looks like this:

function add_label([String]$label_text, [Int]$label_location_x, [Int]$label_location_y, [Int]$lable_size) {
    $label              = New-Object System.Windows.Forms.Label
    $label.AutoSize     = $true
    $label.Location     = New-Object System.Drawing.Point($label_location_x,$label_location_y)
    $label.Size         = New-Object System.Drawing.Size($lable_size,20)
    $label.Text         = $label_text

    $label
}
$label_product = add_label("Product: ", $label_product_location, 20, $LableSize)
$GroupBoxSetting.Controls.Add($label_product)

It does not throw any error, however the label is not displayed. Instead "product: 30 20 50" is displayed in the GUI instead of $groupBoxSetting Text.

I was wondering, is there any way to create a function, which returns the Forms object, so that we do not have to write the same code block again and again for each Forms object.

2
  • 2
    You're calling your function incorrectly, powershell doesn't use the function(x, y, z) syntax. Instead it should look like this: add_label -label_text "Product: " -label_location_x $label_product_location -label_location_y 20 -lable_size $LableSize Commented Mar 7, 2018 at 15:49
  • For cleaner syntax try using splatting like this: $params = @{ 'label_text'='hello'; 'label_location_x'=50; 'label_location_y'=50; 'lable_size'=10; } add_label @params May not look clean in the comments because I don't know how to post multi-line code comments. You can find out more about splatting here Commented Mar 7, 2018 at 16:19

1 Answer 1

1

You're calling your function incorrectly, powershell doesn't use the brackets around the parameters.

Doing this is causing everything inside the brackets to be sent as a single object to the first parameter.

You can use named parameters, which is easy to tell what is being passed to which param:

add_label -label_text "Product: " -label_location_x $label_product_location -label_location_y 20 -lable_size $LableSize

Or positional parameters, which is less to type, but harder to interpret if you don't know the function params already:

add_label "Product: " $label_product_location 20 $LableSize

See about_parameters for more info on this.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.