如何在后台作业脚本块中使用文件中的函数
How to use functions from a file in a background-job scriptblock
我在脚本块中使用文件中的函数时遇到问题。
函数文件名: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
创建的作业有自己的作用域,不继承您本地作用域中定义的函数。您可以在作业脚本块中加载函数或使用 -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
我在脚本块中使用文件中的函数时遇到问题。
函数文件名: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
创建的作业有自己的作用域,不继承您本地作用域中定义的函数。您可以在作业脚本块中加载函数或使用 -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