How do I create a job with a Name (like -Name parameter in Start-Job cmdlet). I’m really surprised that Start-Job does not provide a way to pass arguments to scriptblock.
Thanks, somehow I missed that part.
I still trying to figure out how to use Start-job directly (Invoke-Command use in this case seems to be a “hack” rather then clean instantiation of the job).
Is documentation for Start-Job is wrong or why following snippet works fine below and passing ArgumentList just fine to scriptblock even though documentation state that -ArgumentList is used only in case -FilePath parameter is used?
Invoke-Command isn’t a “hack.” It’s the preferred way to start a job that will deal with one or more remote computers; it’s also completely normal to use it against the local computer. Start-Job isn’t particularly more or less “clean.”
Because I tend to administer more than just the local computer, I tend to rely on Invoke-Command a lot. So, I haven’t played with Start-Job much. I tend to stick with what I know, and what I know works, rather than beat myself up making other stuff work. I find Invoke-Command’s argument-passing to be a lot more declarative and a lot cleaner, too.
Your problem isn’t with passing arguments to the job. The problem is that your function is malformed (missing one closing curly brace, and the “param” keyword). This revision works fine for me:
$computerNames = @('.')
$func = {
function DoCleanup
{
param (
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]$computerName
)
Write-Output "Starting to clean up space on $computerName"
}
}
foreach ($computerName in $computerNames)
{
Start-Job -ScriptBlock {DoCleanup $args[0]} -ArgumentList $computerName -Name “$computerName” -InitializationScript $func
}