1
votes

We are trying to write a background job in PowerShell using Start-Job. This job consumes a cmdlet. For some reasons, the cmdlet is not recognized. However the same cmdlet works when accessed directly.

Code Snippet : Start-Job -ScriptBlock { }

Error :

The term 'commandletName' 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. + CategoryInfo : ObjectNotFound: (commandletName:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException + PSComputerName : localhost

Do i need to import something separately specific for background jobs?

1

1 Answers

4
votes

Start-Job starts a whole new PowerShell session, so any cmdlets that have been imported/created have to be re-imported in the job itself.

You could pull this in using the $using scope.

function Write-HelloWorld {
    "Hello World"
}

Start-Job -ScriptBlock {
    ${function:Write-HelloWorld} = ${using:function:Write-HelloWorld}

    Write-HelloWorld
}