2

How do you use using module with $PSScriptRoot?

using module $PSScriptRoot/../myfolder/base.psm1
# or: using module "$PSScriptRoot/../myfolder/base.psm1"

If I do this, I get this error:

using module $PSScriptRoot: is not a valid value for using name

Thanks to @DavidBrabant I have tried the following:

$scriptBody = "using module /Users/name/Development/tools/powershell/base/base.psm1"
$script = [ScriptBlock]::Create($scriptBody)
. $script

Class Go : MyBaseClass {
    ...

Unfortunately I get:

Unable to find type [MyBaseClass].PowerShell
Ignoring 'TypeNotFound' parse error on type 'MyBaseClass'. Check if the specified type is correct. This can also be due the type not being known at parse time due to types 

Thanks to and @MathiasR.Jessen I tried with "\" with same result. I should say that I am on a mac computer if that makes any different.

Chris G.
  • 23,930
  • 48
  • 177
  • 302
  • 2
    Using module statement cannot include any variables. Its values must be static. There is a workaround. See here: https://info.sapien.com/index.php/scripting/scripting-classes/import-powershell-classes-from-modules – David Brabant Sep 19 '19 at 09:23
  • 1
    The `using module` directive [doesn't seem to respect `/` as a path separator](https://github.com/PowerShell/PowerShell/issues/7424), try with `using module $PSScriptRoot\..\myfolder\base.psm1` or `using module ..\myfolder\base.psm1` – Mathias R. Jessen Sep 19 '19 at 09:24

1 Answers1

0

This answer is based on David's comment on the question.

"To use variable values in a Using module statement, create a script block that includes the Using module statement and dot-source it into the script. (Thanks to Bartek Bielawski for this solution.)"

Param (
    [parameter(Mandatory)]
    [string]
    $ModuleName
)

$scriptBody = "using module $ModuleName"
$script = [ScriptBlock]::Create($scriptBody)
. $script

...

SOURCE: https://info.sapien.com/index.php/scripting/scripting-classes/import-powershell-classes-from-modules

derekbaker783
  • 8,109
  • 4
  • 36
  • 50