【问题标题】:Passing variable to several scriptblocks used in remote sessions Powershell将变量传递给远程会话Powershell中使用的几个脚本块
【发布时间】:2012-10-05 09:56:38
【问题描述】:

我有一个从域服务器运行并在域服务器上“工作”的脚本。

工作被划分为脚本块中的作业,这些作业使用存储的 PSsession 通过调用命令调用。

结果记录在域服务器上的日志文件中,该日志文件名中包含日期时间戳。

现在,我需要添加另一个日志,该日志需要驻留在完成工作的遥控器上。日志名称格式还需要包含日期和时间戳。

我的问题是将日志名称传递给每个作业,以便它们写入同一个文件。我玩过 -ArgumentList、@args 和 $args,我可以正常运行但什么也不做,所以我没有正确传递日志文件名。

以下是我如何构建脚本的超级简化版本。

将 Start-Job 嵌套在另一个脚本块中是否错误?如何将我的唯一日志文件名传递给这些脚本块以捕获成功/失败和特定点?


#log file names, ps session and other variables declared here  

  $DoDomainWorkScriptBlock = {

    Try {

            start-job -name DoDomainWorkjob -scriptblock{

          $command = "C:\Program Files\someprogram\someprogram.exe"

          & $command  -f someargs


            If ($? -ne "True") {Throw 'Do work failed’}

            " Do non-domain work job completed. "

            }

        } Catch {$Error[0] | Out-File $ErrorLog -Append}

    }

#other jobs nested in other scriptblocks like the one above here

Invoke-Command -session $RemoteSession -scriptblock $DoDomainWorkScriptblock | Out-File $DomainProgressLog -Append

Invoke-Command -session $RemoteSession -command{Wait-Job -name DoDomainWorkjob } | Out-File $DomainProgressLog -Append

Invoke-Command -session $RemoteSession -command{Receive-Job -Name DoDomainWorkjob } | Out-File $DomainProgressLog –Append


#invoke start, wait, and receive job commands for the other jobs

【问题讨论】:

    标签: session logging powershell parameter-passing remoting


    【解决方案1】:

    您可以像这样将参数传递给脚本块:

    $code = {
      param( $foo )
      Write-Host $foo
    }
    
    $bar = "bar"
    Invoke-Command -ScriptBlock $code -ArgumentList $bar
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      相关资源
      最近更新 更多