How to Temporarily Prevent SMB File from Being Locked in Use on Windows

powershellserver-message-blockwindows

I have a file \\server\share\myApp\app.exe that a handful of people run directly from the share. I need to update that file occasionally, but it is usually locked due to the open SMB sessions.

My normal procedure for similar SMB locked files is to close the files and sessions locking them like:

$openAppFiles = Get-SmbOpenFile | Where Path -like 'D:\Shares\myApp\*' 
$appSessions  = $openAppFiles | Select SessionID -Unique

Close-SmbOpenFile -FileID $openAppFiles.FileID -Force
Close-SmbSession -SessionID $appSessions.SessionID -Force

Extract-Archive $newZip -Destination 'D:\Shares\myApp\' -Force

But lately, I have run into issues where a client is able to reconnect and lock one or more of the files I'm updating within that tiny window. I can test trying to just rename a file for example:

Rename-Item .\app.exe .\app.exe.bak

[Error] Rename-Item : The process cannot access the file because it is being used by another process.

Is there a way for me to temporarily block clients from accessing these files?

I've considered turning off the share temporarily, but I would have to do it after-hours. I can also just keep re-running it until it works, but that doesn't necessarily solve the issue either. What other options can I try?

Best Answer

You could try adding Deny Everyone entry to share's ACL:

Block-SmbShareAccess -Name AppShare -AccountName Everyone -Force

Next, proceed with disconnecting connected users like you do in your script.

After the app is updated, remove Deny Everyone entry from ACL:

Unblock-SmbShareAccess -Name AppShare -AccountName Everyone -Force