Powershell Lock Function

A handy Powershell function to lock / unlock using .NET, to prevent concurrent read/writes to files or anything else you like.

function handleThreadLock{
    Param(
        [switch]$setLock,
        [switch]$releaseLock,
        [string]$lockName="defaultLockName",
        [int]$timeOut=600
    )
    if($setLock){
        #register a thread lock
        $script:threadLock = New-Object System.Threading.Mutex($false, $lockName)
        $waited = 0
        while($true){
            try{$lockState = $script:threadLock.WaitOne(1000)}catch{$lockState=$False}
            if($lockState){
                break
            }else{
                $waited+=1
                if($waited -gt $timeOut){
                    Throw "failed to get a thread within $timeOut seconds!"
                }
            }
        }
    }  
    if($releaseLock){
        #release a thread lock
        [void]$script:threadLock.ReleaseMutex()
    }  
}

In your script, call it like this:

try{
    handleThreadLock -setLock
}catch{Throw "Failed to set lock!"}

try{
    add-content -Path "c:\yourfile.txt" -Value "log entry" -ErrorAction Stop
}finally{
    handleThreadLock -releaseLock
}
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Dead-Red
Dead-Red
6 years ago

Hello,

Nice script, thank’s for your help 😉

But you have just forgotten a comma “,” after the string :

“defaultLockName”

Regards,