【问题标题】:How do I import functions in separate files into a main file and run them as jobs?如何将单独文件中的函数导入主文件并将它们作为作业运行?
【发布时间】:2016-08-25 15:03:48
【问题描述】:

我已经问过一个有点相关的问题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

【问题讨论】:

  • 您是否尝试过使用完整(而非相对)路径?即:. c:\func1.ps1
  • 该死的就是这样。有没有办法可以使用函数文件的相对路径?它们都将位于同一个文件夹中。
  • 在下面查看我的答案。相信我,我对 PS 相对/绝对路径感到很痛苦。
  • Here 是一个很好的同时点源多个文件的例子。

标签: powershell powershell-3.0 jobs job-scheduling


【解决方案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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-14
    • 2020-03-29
    • 2018-07-10
    • 2012-10-17
    • 1970-01-01
    • 2014-01-13
    • 2016-09-05
    • 2015-12-31
    相关资源
    最近更新 更多