Write to a file with multiple jobs in PowerShell

parallel-processing, powershell, windows

Solution

You could synchronize file access using a Mutex e.g.

$mutex = new-object System.Threading.Mutex $false,'SomeUniqueName'
...
nr = $WorkflowData['_Number']
$mutex.WaitOne() > $null
$nr >> C:\Configuration\nrFile.txt
$mutex.ReleaseMutex()

Problem

We have an activity that runs the following code: ``` $nr = $WorkflowData['_Number'] ## Write to text $nr>>C:\Configuration\nrFile.txt ``` Basically it gets a unique number that should be added to a file. The problem is that this activity runs in multiple workflows that can run at the same time. This resulted in a lot of errors saying that the `nrFile.txt` is opened by another job running at the same time. Is there some way to write from multiple workflows to the same file simultaneously? Or maybe to queue them up somehow?

Original source