title: PowerShell Write to Same File Multiple Jobs
body: <p>I have a script that pulls one line of data from a file on multiple servers. I have a single-threaded version that works just fine, but I want to get it to run faster. Since I only need one line of one file from each server, I'm sure I could run this in parallel. I pulled code from multiple places to get a multi-threaded script running, but when I try to get all the results to print to one output file, nothing prints. I wonder if anyone can look at my code to tell me why this same script, without the Jobs, works fine, but after adding jobs, it doesn't.</p>
  
  <pre><code>$sb =  {
     Param($computer, $fileName, $outLog)
     net use "\\$computer\c$" **** /user:****
     if(test-path \\$computer\c$\sc\$fileName){
        [xml]$periods = Get-Content \\$computer\c$\sc\$fileName
        $endDate = $periods.PeriodDetail | select -last 1
        $output = "$computer;$endDate"
     }
     Else {
        $output = "$computer;$fileName Not Found"
     }
     #Synchronize file usage
     $mutex = new-object System.Threading.Mutex $false,'SomeUniqueName'
     $mutex.WaitOne() &gt; $null
     #Write data to log
     Out-File -Append -InputObject $output -FilePath $outLog
     #Release file hold
     $mutex.ReleaseMutex()
  
     net use "\\$computer\c$" /de 
  }
  
  foreach($computer in $computerName){
     while ((Get-Job -State Running).Count -ge 20) {
        Start-Sleep -Seconds 5;
     }
     Start-Job -Scriptblock $sb -ArgumentList $computer,$fileName,$outLog
  }
  Get-Job | Wait-Job | Receive-Job
  </code></pre>