Mutex in PowerShell
Lately, I was having problem where I am only allowed to spawn a single process in my PowerShell script. Any concurrent execution of the process will cause deadlock of a particular resource.
The easiest solution to this is by wrapping your process call (a.k.a. critical region) in a Mutex, which utilise the .NET framework
$mutex = new-object -TypeName System.Threading.Mutex -ArgumentList $false, “RandomGlobalMutexName”; $result = $mutex.WaitOne(); #Begin Critical Region Write-Host "Hello World" Sleep 60 #End Critical Region $mutex.ReleaseMutex();
Put this in a file called hellomutex.ps1 and spawn up multiple powershell session and try to run the script simultaneously. You should get sequential write of "Hello World" in different powershell session.
Hope this helps!













