Forum Discussion
The 'using module' statement into a ThreadJob's ScriptBlock
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!
- ManuelBerfeldeCopper ContributorDid you ever find a solution for this?
Struggeling myslef here.- LainRobertsonSilver Contributor
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
- ManuelBerfeldeCopper Contributor
My usecase is classes - so... thanks a lot 🙂