2012-04-17 20 views
2

私はこのパワーシェルコードを持っています。現在、$ agent変数は評価されていません。Start-Jobの変数

foreach($agent in $agentcomputers){ 
Write-Output 'Starting agent on '$agent 
#psexc to start the agent 
Start-Job -ScriptBlock {& psexec $agent c:\grinder\examples\startAgent.cmd} 
} 

これは、私が外部のPowerShellスクリプトを呼び出さない以外は、私の問題と似ています。

http://sqlblog.com/blogs/aaron_bertrand/archive/2011/01/29/powershell-start-job-scriptblock-sad-panda-face.aspx

私は、それを中に追加の$エージェントの[0] $引数を使用して-ArgumentListパラメータを追加しようとしたが、それは動作しませんでした。

ご協力いただきありがとうございます。

編集/ Replysは...


これは$ agentcomputers、コンピュータ名のリストだけです。それぞれはそれ自身の行です。

$agentcomputers = Get-Content c:\grinder-dist\agent-computers.txt 

は私もこれを試してみました - と$ argsを[0]ここで

Start-Job -ScriptBlock {& psexec $args[0] c:\grinder\examples\startAgent.cmd} -ArgumentList @($agent) 
+0

'$ agent'には何が格納されていますか? –

+0

'$ args'配列またはparamブロックを使用してArgumentListパラメータを使用する必要があります。 –

+0

$ agent変数のスコープを変更することもできます。$ global:agent。 –

答えて

4

を評価しませんソリューションです。 Andyが言ったように、私は$ args配列に-ArgumentListパラメータを使用する必要がありました。この他のスレッドは役に立ちました:Powershell: passing parameters to a job

foreach($agent in $agentcomputers){ 
$agentslash = "\\"+$agent 
$args = ($agentslash,"c:\grinder\examples\startAgent.cmd") 
Write-Output 'Starting agent on '$agent 

#psexc to start the agent 
$ScriptBlock = {& 'psexec' @args } 

Start-Job -ScriptBlock $ScriptBlock -ArgumentList $args 

} 
7

ここで私はそれをやります。 まず、すべて整列してきれいです。

$agents = Get-Content c:\grinder-dist\agent-computers.txt 
$jobs = { 
    Param($agent) 
     write-host "Starting agent on" $agent 
     & psexec \\$agent c:\grinder\examples\startAgent.cmd 
} 
foreach($agent in $agents) { 
    Start-Job -ScriptBlock $jobs -argumentlist $agent | Out-Null 
} 
Get-Job | Wait-Job | Receive-Job 

また、変数を作成せずに1行に入力するだけでも可能です。

(Get-Content c:\grinder-dist\agent-computers.txt) | %{ Start-Job -ScriptBlock { param($_) write-host "Starting agent on" $_; & psexec \\$_ c:\grinder\examples\startAgent.cmd } -argumentlist $_ | Out-Null } 
Get-Job | Wait-Job | Receive-Job 

この最後の例では、このようにして同時に実行するスレッドの数を管理できます。

$MaxThreads = 5 
$agents = Get-Content c:\grinder-dist\agent-computers.txt 
$jobs = { 
    Param($agent) 
     write-host "Starting agent on" $agent 
     & psexec \\$agent c:\grinder\examples\startAgent.cmd 
} 
foreach($agent in $agents) { 
    Start-Job -ScriptBlock $jobs -argumentlist $agent | Out-Null 
    While($(Get-Job -State 'Running').Count -ge $MaxThreads) { 
      sleep 10 
    } 
    Get-Job | Wait-Job | Receive-Job 
}