输入在脚本块内更改

Input gets changed inside a scriptblock

我有这个带有脚本块的脚本:

$RoboArgs = @{
  Source = '01'
  Target = '02'
  ExtraArgs = '/e', '/purge'
}
Write-Host @RoboArgs
Start-ThreadJob -InputObject $RoboArgs -ScriptBlock {
  . robocopy_invoke.ps1
  Write-Host @input
} | Receive-Job -Wait -AutoRemoveJob

我想使用输入参数 (Invoke-Robocopy @RoboArgs) 调用 robocopy_invoke.ps1 模块中定义的函数,但是输入参数的内容在进入脚本块。 这是输出:

-Target: 02 -ExtraArgs: /e /purge -Source: 01
System.Management.Automation.Runspaces.PipelineReader`1+<GetReadEnumerator>d__20[System.Object]

为什么两次 Write-Host 调用的输出不同? 我怎样才能让第二个像第一个一样?

您使用“-InputObject”将对象通过管道传输到作业中(使用 $input 检索)。 所以 Start-ThreadJob -InputObject $RoboArgs -ScriptBlock {} 等同于 $RoboArgs | Start-ThreadJob -ScriptBlock {}

您需要的是“-ArgumentList”(使用 $args 检索):

$RoboArgs = @{
  Source = '01'
  Target = '02'
  ExtraArgs = '/e', '/purge'
}
$RoboArgs

Start-ThreadJob -ArgumentList $RoboArgs -ScriptBlock {
  $args
} | Receive-Job -Wait -AutoRemoveJob

示例 2(解压 $args 数组)

$RoboArgs = @{
  Source = '01'
  Target = '02'
  ExtraArgs = '/e', '/purge'
}
Write-Host @RoboArgs

Start-ThreadJob -ArgumentList $RoboArgs -ScriptBlock {
  $robo = $args[0]
  Write-Host @robo
} | Receive-Job -Wait -AutoRemoveJob

示例 3(显式定义参数而不是使用 $args)

$RoboArgs = @{
    Source    = '01'
    Target    = '02'
    ExtraArgs = '/e', '/purge'
}
Write-Host @RoboArgs


Start-ThreadJob -ArgumentList $RoboArgs -ScriptBlock {
    param ( $myRoboArgs )
    Write-Host @myRoboArgs
} | Receive-Job -Wait -AutoRemoveJob