Powershell GUI - Function outsourcing

Dear forum,
I have an issue, which I hope, you guys can help me with:
I am having a window, named “$objForm”

$objForm = New-Object System.Windows.Forms.Form

in which I have implemented a button (called $btn5). By pushing this button, a function (called done) shall be opened, which generates a “close/done-button” to this form (This works fine, as long, as the code is not outsourced as a function)

in the main window, I have set

$WindowName ='objForm'

to call the function (when pushing the button), I have

$btn5.add_Click{(done $WindowName)}


The function looks like this :

function done
param ($WindowName)

$done = New-Object System.Windows.Forms.Button
$doneFont = New-Object System.Drawing.Font("Calibri",18,[System.Drawing.FontStyle]::Bold)
$done.Font = $doneFont
$done.Location = New-Object System.Drawing.Size(320,200)
$done.Size = New-Object System.Drawing.Size(150,50)
$done.Text = "DONE!"

write-host 'Hello'
write-host $WindowName


When running the program (the main window), and pushing the button, I get the following:

you cannot call a method on a null-valued expression.
At C:\temp\done.ps1:22 char:1
+CategoryInfo : InvalidOperation: (:) [], RuntimeException
+Fully QualifiedErrorID: InvokeMethodOnNull


What I do not understand is: Why can I do a ==> write-Host $WindowName <== in the function
But a ==> $WindowName.Controls.Add($done) <== does not work in the function?


Thank you very much for any help

$WindowName is a string here as you have defined and won’t have properties and methods of a Form. You should pass a WindowsForm object to the function to consume its members.

$btn5.add_Click{(done $objForm)}