Function not recognized in start-job
Asked Answered
G

3

4

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.

Greenling answered 6/9, 2012 at 5:51 Comment(0)
S
5

you can use InitializationScript to import module:

PS II> Start-Job -InitializationScript {import-module "c:\module.psm1"} -script {Uptime}
Sloane answered 6/9, 2012 at 11:6 Comment(0)
I
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.

Incorruption answered 6/9, 2012 at 7:1 Comment(0)
G
2

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

Gildea answered 6/9, 2012 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.