powershellpowershell-5.1start-job

Question on use of Powershell start-job -scriptblock or sajb


I see many examples along the lines of:

Get-ChildItem -Filter "*.txt" | ForEach-Object { sajb {ren $_.fullname ($_.directoryname + "\" + "temp_" + $_.name + ".newext") } }

or what I think should be equivalent, using start-job -scriptblock:

Get-ChildItem -Filter "*.txt" | ForEach-Object { Start-Job -ScriptBlock {ren $_.fullname ($_.directoryname + "\" + "temp_" + $_.name + ".newext") } }

But these don't work for me. I get output like this and nothing happens to the files:

enter image description here

or this for my actual usecase:

enter image description here

If I remove the sajb block, then it works fine in series and does exactly what you'd expect. It's only when I try to run all commands in the loop in parallel that it fails.

The same operations do work fine from the Command prompt using:

for %x in ("*.txt") do (start "Convert" cmd /c "ren "%x" "temp_%x.newext"")

My purpose is to do this for some commands that run slowly in series but would run quickly in parallel using ffmpeg and sox, which also work fine in the for loop from the command prompt. I just can't get it working in PowerShell, even in the simple case like the file rename example above. What am I doing wrong with the start-job / sajb?

If it matters, I want to run this as a single PowerShell command from the PS prompt. I do not want to create a PowerShell script.

I see other posts with what look like similar questions, but I don't think they ever received functional answers, or if those answer are correct, I don't understand how to apply them to my situation:

Powershell start-job scriptblock not executing

Powershell Start-Job not executing scriptblock


Solution