Jan 24 2022 12:09 PM - edited Jan 25 2022 06:38 AM
Hi everyone!
I have a question about the 'using module' statement in Powershell.
I have many class in different .psm1 files, wich works perfectly with 'using module' statement. But I need to import my class into a ThreadJob's ScriptBlock and 'using module' do not be used after any statements in the script.
I do not want use the 'import-module' statement, because this statement not import class from .psm1 files, only from ps1. I would have to change all my class files to .ps1 and the 'using module' do not work with .ps1. What would entail more and more problems.
'using module' also works with relative path, import-module do not.
Exists one way to use the 'using module' into a ScriptBlock or another way to delegate the imports between the scopes?
Thanks for help!
Apr 07 2024 01:18 PM
Apr 07 2024 05:06 PM
It is doable, but not necessarily advisable.
If the module's simple, such as only defining classes and functions then you'll be fine. But if you're doing more complex work like using database connections and other limited resource operations then you can run into issues if you're not careful - and overhead may become an issue, too, if initialisation operations take a long time.
Still, here's some example code you can use within your job's [scriptblock] to get around PowerShell's "using must be the first line" error.
$Script = [scriptblock]::Create("using module 'D:\Data\Temp\Forum\Forum.psm1'");
. $Script *> $null;
Cheers,
Lain
Apr 11 2024 05:05 AM - edited Apr 11 2024 05:07 AM
My usecase is classes - so... thanks a lot 🙂