2016-08-25 24 views
1

我已經問了一個有點相關的問題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

您是否嘗試過使用完整(而不是相對)路徑?那就是:'。 c:\ func1.ps1' –

+0

該死的就是這樣。有沒有一種方法可以使用函數文件的相對路徑?他們都將在同一個文件夾中。 – red888

+0

請參閱下面的答案。相信我,我對PS相對/絕對路徑有很多痛苦。 –

回答

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") 
相關問題