簡體   English   中英

如何在后台作業腳本塊中使用文件中的函數

[英]How to use functions from a file in a background-job scriptblock

我在腳本塊中使用文件中的函數時遇到問題。 Function 文件名: functions.ps1

我更喜歡在文件中使用函數,通常它是有效的。 但是在我用於作業的腳本塊中,我有錯誤。 你能幫我在腳本塊中使用函數嗎?

. .\functions.ps1
$ip = "10.0.0.24"
$scriptblock = { get-ostype -ip $args[0] }
Start-Job -name "name" -ScriptBlock $scriptblock -ArgumentList $ip

作業錯誤:

The term 'get-ostype' 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          : ObjectNotFound: (get-ostype:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : localhost

創建的作業有自己的 scope,它不繼承本地 scope 中定義的功能。 您可以在作業腳本塊中加載函數,也可以使用-InitializationScript參數。

# Option 1:
$ip="10.0.0.24"
$scriptblock = {get-ostype -ip $args[0]}
$initializationscript = {. c:\path\functions.ps1}

Start-Job -InitializationScript $initializationscript -ScriptBlock $scriptblock -ArgumentList $ip

# Option 2:
$ip="10.0.0.24"
$scriptblock = {. c:\path\functions.ps1; get-ostype -ip $args[0]}

Start-Job -ScriptBlock $scriptblock -ArgumentList $ip

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM