0

I have written a script that will execute a script in the remote machine. Script is organised in the remote machine in the following way,
lib - this is where library filea are located
tests - this is where test scripts are located

The script in the remote machine(in the tests folder) imports other modules from library folder like

Import-Module -Name "..\lib\commonlib.psm1".

Now when the script in the tests folder remote machine is invoked, there is any error

Import-Module : The specified module '..\lib\commonlib.psm1' was not loaded because no valid module file was found in any module directory(directory lib and commonlib.psm1 are present in the correct path)

How can this issue be resolved?

Below is the command to run the script in the remote machine.

$job = "c:\scripts\test.ps1" $cmdRes = Invoke-Command -ComputerName $remoteMachineName -ScriptBlock {& $args[0]} -ArgumentList $job -AsJob

1
  • 2
    Does the script work if module path is specified as absolute path?
    – vonPryz
    Nov 6, 2013 at 10:15

2 Answers 2

1

If you can rely on v3 then load the module relative to your script's location using $PSScriptRoot e.g.

Import-Module "$PSScriptRoot\..\lib\commonlib.psm1"

If you need to work on V2 do this:

$ScriptDir = Split-Path $MyInvocation.MyCommand.Path -Parent
Import-Module "$scriptdir\..\lib\commonlib.psm1"
1

Another approach I take with PowerShell v2 is to use Push-Location and Pop-Location when relative references are used with in the script. This way you can reference everything as simple as possible within the script and not have to worry about changes in context causing problems. To continue Keith's v2 example:

Push-Location -Path $(Split-Path $MyInvocation.MyCommand.Path -Parent)
Import-Module ..\lib\commonlib.psm1

.\SomeOtherScript.ps1 $var # call to another script
... #rest of script
Pop-Location

The Pop-Location isn't needed, but leaves the current directory unchanged after script execution which can be important in some instances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.