How to return an object in powershell

Ankit

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.

James C.

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related