'Powershell code doesn't work when migrated to a module
Work continues on migrating my HTA to an XAML-based form...
All the controls I require are imported from a file with the XAML in it.
I have added a button and an associated Add_Click event to close the form:
$btnQuit.Add_Click({
Write-Host 'Closing down...' -Fore Red
$Form.Close()
})
That works fine if that code is part of my script.
However, if I move that code to a module as a function like this:
Function DoExit{
Write-Host 'Closing down...' -Fore Red
$Form.Close()
}
which the script imports thus:
$Global:ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
Import-Module -Name $ScriptDir\\FunctionBlock.psm1 -Verbose -Scope Global
and then try to call it thus:
$btnQuit.Add_Click($function:DoExit)
The error message I get is:
You cannot call a method on a null-valued expression.At [path to my project goes here]FunctionBlock.psm1:20 char:2
+
$Form.Close()
+
~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) \[\], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
My guess is that this is either a scope thing or a syntax thing?
I've tried all manner of combinations of syntax which I've gleaned from this resource and others, to no avail.
Solution 1:[1]
@zett42
Thanks for the pointers.
Both of the suggested routes ended up producing the same error but it would seem I hadn't tried every combination of syntax! I changed the Add-Click to this:
$btnQuit.Add_Click({DoExit($Form)}.GetNewClosure())
and the 'DoExit' function to this:
Function DoExit($Form){
Write-Host 'Closing down...' -Fore Red
$Form.Close()
}
and it now works!
It seems that I am still unable to vote for posts but, as soon as I can, I will.
Thanks again!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VBScab |
