如何在Powershell Start-job中调用模块功能

时间:2017-11-08 14:14:36

标签: powershell

我尝试将模块的方法/功能发送给作业 如何在作业中执行方法/功能?

# Create a module with 1 method.
$m = New-Module -ScriptBlock{
        function start(){
            "started"
        };
    } -AsCustomObject

# Start a job and send in the function/method.
Start-Job -ScriptBlock{
    $func = $args[0]
    "<args0:$func>" # The function/method seems to contain what I want.
    $func # <------------ How do I call $func/$m.start?
} -ArgumentList $m.start

运行上述内容然后job 498 | Receive-Job -Keep给出:

PS C:\temp\> job 500 | Receive-Job -Keep
<argsO:System.Object start();>

RunspaceId          : 9271e389-cc97-4d2a-9396-5f0ce3f0ae5c
Script              : 
                                      "started"

OverloadDefinitions : {System.Object start();}
MemberType          : ScriptMethod
TypeNameOfValue     : System.Object
Value               : System.Object start();
Name                : start
IsInstance          : True

所以据我所知,我确实有函数/方法。

2 个答案:

答案 0 :(得分:0)

start是一个脚本方法。您需要将start作为方法调用。

$M | Get-Member
$M.start()

# Create a module with 1 method.
$m = New-Module -ScriptBlock{
        function start(){
            mkdir 'C:\Vincent\job'
        };
    } -AsCustomObject

# Start a job and send in the function/method.
Start-Job -ScriptBlock{
    $func = $args[0]
    "<args0:$func>" # The function/method seems to contain what I want.
    $func # <------------ How do I call $func/$m.start?
} -ArgumentList $m.start()

Importing Modules using -AsCustomObject

答案 1 :(得分:0)

发布问题后我发现:

Start-Job -ScriptBlock{
    $func = $args[0]
    "<args0:$func>" # The function/method seems to contain what I want.
    $script = [scriptblock]::Create($func.Script);
    $script.Invoke()
} -ArgumentList $m.start

但正如我的同事所说:嗯谁应该理解这个?
难道没有更复杂的方法来运行方法吗?