如何将单独文件中的函数导入主文件并将其作为作业运行?

时间:2016-08-25 15:03:49

标签: powershell powershell-v3.0 jobs job-scheduling

我已经问了一个有点相关的问题here

我在一个主文件中的单独文件中有一堆函数如何在主文件中将这些函数作为作业调用?

这是func1.ps1:

function FOO { write-output "HEY" }

这是func2.ps1:

function FOO2 { write-output "HEY2" }

这是testjobsMain.ps1

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

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

$var

当我运行testjobsMain.ps1时,我收到此错误:

. : 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

1 个答案:

答案 0 :(得分:1)

绝对路径对我有用:

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

如果需要,在testjobsMain.ps1中,您可以使用$PSScriptRoot自动变量替换绝对相对路径。例如:

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