red888 red888 - 3 months ago 9
PowerShell Question

How do I import functions in separate files into a main file and run them as jobs?

I already asked a somewhat related question here.

I have a bunch of functions in separate files dot sourced in one main file how would I call those function in the main file as jobs?

Here is func1.ps1:

function FOO { write-output "HEY" }


Here is func2.ps1:

function FOO2 { write-output "HEY2" }


Here is testjobsMain.ps1

$Functions = {
. .\func1.ps1
. .\func2.ps1
}

$var = Start-Job -InitializationScript $Functions -ScriptBlock { FOO } | Wait-Job | Receive-Job

$var


When I run testjobsMain.ps1 I get this error:

. : The term '.\func1.ps1' 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.
At line:2 char:4
+ . .\func1.ps1
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\func1.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

. : The term '.\func2.ps1' 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.
At line:3 char:4
+ . .\func2.ps1
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\func2.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Running startup script threw an error: The term '.\func2.ps1' 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 : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken

Answer

Absolute paths worked for me:

$Functions = {
    . c:\foo.ps1
}
$var = Start-Job -InitializationScript $Functions -ScriptBlock { FOO } | Wait-Job | Receive-Job
$var

If needed, in testjobsMain.ps1 you can substitute relative paths with absolute by using $PSScriptRoot automatic variable. For instance:

$Functions = [scriptblock]::Create(" . $PSScriptRoot\foo.ps1 `n . $PSScriptRoot\bar.ps1 `n")
Comments