将值传递给运行/后台脚本块的最佳方法是什么?

时间:2012-12-15 10:18:15

标签: powershell

我有脚本,可以通过start-job启动多个正在运行的脚本块。

将一些变量/值传递给正在运行的后台脚本块的最佳方法是什么?

有一些选项,如服务代理/队列,文件等。有更轻松的方式吗?

例如,

$sb = {
    $Value = $args[0] # initial value
    while ($true) 
    {
        # Get more values from caller
        $Value = .....
    }
}
start-job -ScriptBlock $sb -ArgumentList $initValue
# There are more values to send to the script after the script block is started.
while (moreVaulesAvailable)
{
     # $sb.Value = .... newly generated values ? 
}

Start-Job启动了另一个PowerShell流程。是否有任何内置机制在PS进程之间传递值?

1 个答案:

答案 0 :(得分:3)

您可以使用MSMQ执行此操作。 PowerShell V3附带了一个MSMQ模块。以下是如何使用MSMQ将消息传递给后台任务的示例:

$sb = {
    param($queueName)
    $q = Get-MsmqQueue $queueName
    while (1) {
        $messages = @(try {Receive-MsmqQueue -InputObject $q -RetrieveBody} catch {})
        foreach ($message in $messages)
        {
            "Job received message: $($message.Body)"

            if ($message.Body -eq '!quit')
            {
                return
            }
        }
        Start-Sleep -Milliseconds 1000
        "Sleeping..."
    }
}

$queueName = 'JobMessages'
$q = Get-MsmqQueue $queueName
if ($q)
{
    "Clearing the queue $($q.QueueName)"
    $q | Clear-MsmqQueue > $null    
}
else
{
    $q = New-MsmqQueue $queueName
    "Created queue $($q.QueueName)"
}

$job = Start-Job -ScriptBlock $sb -ArgumentList $queueName -Name MsgProcessingJob
"Job started"

$msg = New-MsmqMessage "Message1 for job sent at: $(Get-Date)"
Send-MsmqQueue -Name $q.Path -MessageObject $msg > $null

Receive-Job $job

$msg = New-MsmqMessage "Message2 for job sent at: $(Get-Date)"
Send-MsmqQueue -Name $q.Path -MessageObject $msg > $null

$msg = New-MsmqMessage "!quit"
Send-MsmqQueue -Name $q.Path -MessageObject $msg > $null

Wait-Job $job -Timeout 30
Receive-Job $job
Get-Job $job.Name
Remove-Job $job

当我运行此脚本时,我得到以下输出:

C:\PS> .\MsmqQueue.ps1
Clearing the queue private$\jobmessages
Job started

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
4      MsgProcessin... BackgroundJob   Completed     True            localhost            ...
Job received message: Message1 for job sent at: 12/15/2012 17:53:39
Sleeping...
Job received message: Message2 for job sent at: 12/15/2012 17:53:39
Sleeping...
Job received message: !quit
4      MsgProcessin... BackgroundJob   Completed     False           localhost            ...