Function not accessible in a ScriptBlock

Question:

I have a script that has some functions and then multiple jobs in the very same script that use those functions. When I start a new job they don’t seem to be accessible in the [ScriptBlock] that I have for my jobs.

Here’s a minimal example demonstrating this:

The error that I get in PowerShell ISE is:

Answer:

Start-Job run jobs in separate PowerShell processes. So that, jobs do not have access to session state of calling PowerShell session. You need to define functions, which get used by jobs, in every job. An easy way to do that without duplicating the code would be using of -InitializationScript parameter, where all common functions can be defined.

Source:

Function not accessible in a ScriptBlock by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply