1

So I am trying to start-job from a module I wrote.

Copy-Modules.psm1

function startcopy([string] $ShowToCopy) {
  if (-not($ShowToCopy)) { return "No name provided. Doing nothing." }
  } else { return "Name Provided $ShowToCopy" }
}

in the main script I am calling it as follows:

$Copyname = "test"

Start-Job -Name "copy1" -InitializationScript { Import-Module -Name .\Copy-Modules.psm1 } -ScriptBlock {startcopy} -ArgumentList $Copyname

However the arguments never seems to go through. No matter how I format or pass the argument with switch or without I always get the result No name provided. Doing nothing.

Lin sain
  • 11
  • 1

1 Answers1

1

The simplest solution - assuming you need no other functions from your Copy-Modules.psm1 module - is to pass your function's body as Start-Job's -ScriptBlock argument:

Start-Job -Name "copy1" -ScriptBlock $function:startcopy -ArgumentList $Copyname

$function:startcopy uses namespace variable notation to get the startcopy's body as a script block.

Note:

  • This obviates the need to define your startcopy function in the scope of the background job (which is an independent session in a child process that knows nothing about the caller's state), which is what your -InitializationScript script block does.

  • The only limitation of this approach is that the script block won't be named, i.e. the original function name is lost, and $MyInvocation.MyCommand.Name inside the function returns the empty string.


As for what you tried:

  • It is the script block as a whole that receives the (invariably positional arguments passed to -ArgumentList, which you'll have to pass on explicitly to any commands called inside the script block, using the automatic $args variable:
$Copyname = "test"

# Note the use of $args[0]
Start-Job -Name "copy1" `
  -InitializationScript { Import-Module -Name .\Copy-Modules.psm1 } `
  -ScriptBlock { startcopy $args[0] } -ArgumentList $Copyname
mklement0
  • 382,024
  • 64
  • 607
  • 775