问题
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 $servernae}, 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.
回答1:
you can use InitializationScript to import module:
PS II> Start-Job -InitializationScript {import-module "c:\module.psm1"} -script {Uptime}
回答2:
You have to import explicitely your module in the ScriptBlock before calling your function.
回答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.
来源:https://stackoverflow.com/questions/12293701/function-not-recognized-in-start-job