In Powershell (specifically 5.1), I have a custom class Foo, defined in a file like this:
Class Foo {
....
}
And in a script (.ps1 file) I want to use this type for one of the parameters, e.g.:
Param(
[Foo] $Bar
...
The problem is that Param() MUST be the first statement in the script, other than comments or #requires. So how do I tell the script what the definition of Foo is?
1. Putting the class definition in a module and "importing" with #requires doesn't work, because #requires doesn't import classes.
2. Putting anything above the Param() (such as putting the definition of Foo in a separate file and dot-loading it, or using module, or just pasting the definition itself) then prevents the Param() from being recognized.
3. Putting the definition below the Param() list doesn't work because [Foo] isn't defined at the time the Param list is parsed -- PS doesn't allow forward references apparently.
4. Couldn't put the definition inside the Param() list either.
Various workarounds are
1. Do "using module .\foo.psm1" or similar in the shell before running the script.
2. Put the script body in a module; import the module, then call the function.
But note that each requires TWO steps, rather than ONE. I'm looking for the convenience of telling people "run this script" rather than "here, do this sequence of commands".
I want to define $Bar in the script as being of type Foo, because the Foo class definition has a bunch of constructors, so I want the caller to be able to pass in various data types (String, int, whatever) and have PS call the right constructor to turn it into a Foo.