3

I created a function "Get-Uptime" in a module sysinfo.psm1 and imported the module.

C:/pstools> get-command -Module sysinfo

CommandType     Name                                                Definition
-----------     ----                                                ----------
Function        Get-Uptime                                          ...

The function worked fine within Powershell. However, whenever I used the Get-Uptime function in a Start-job -scriptblock {Get-Uptime $servername}, the job failed with the following error

Receive-Job : The term 'get-uptime' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of 
the name, or if a path was included, verify that the path is correct and 
try again.

Could someone please let me know what I've missed? I've searched the net and found a suggestion to write all codes in the scriptblock instead of using a function, but I've tried and got similar errors.

Thank you.

tukan
  • 17,050
  • 1
  • 20
  • 48
Barry Chum
  • 829
  • 3
  • 14
  • 23

3 Answers3

4

you can use InitializationScript to import module:

PS II> Start-Job -InitializationScript {import-module "c:\module.psm1"} -script {Uptime}
walid2mi
  • 2,704
  • 15
  • 15
3

PowerShell jobs run in a separate process, a new powershell.exe is created for each job object, and that process has no idea of a module that was imported in another session.

In order to need the Get-Uptime function, load the module in the Start-Job command.

Shay Levy
  • 121,444
  • 32
  • 184
  • 206
2

You have to import explicitely your module in the ScriptBlock before calling your function.

JPBlanc
  • 70,406
  • 17
  • 130
  • 175