How To Disconnect Users Accessing a Windows Shared Folder using PowerShell
Until I find a WMI (e.g. based on something like Win32_ServerConnection) or .NET object solution that lets me deal with the list of connections as first class objects rather than parsing the text output, I've come up with this solution based around the OpenFiles utility. I'm fairly concerned that it's fragile and not that obvious to modify for different needs but it seems to be working for my narrow scenario at the moment. I've kept the regex with named captures for the other parts of the output as a reference for if you need to use different parameters for openfiles /disconnect (/A /ID /OP).
Note that repeated use of Select-String is something I don't fully understand but is to do with the fact that this is necessary to get access to the named captures. See this RegEx Named Groups with Select-String posting for details. Happy to change it if someone can tell me how!
$computerName = 'ServerName'
$pattern = '^.+ (?<FileId>\d+) (?<User>[^ ]+).+ (?<OpenFile>C:.+\\SpecificFolder\\.*)$'
$openfiles = openfiles /query /s $computerName /v | Select-String -Pattern $pattern | ForEach-Object {[void]($_.Line -match $pattern); $matches['OpenFile']}
$openfiles | Sort-Object -Unique | ForEach-Object { openfiles /disconnect /s $computerName /a * /op `"$_`"}
Related videos on Youtube
Martin Hollingsworth
Updated on September 17, 2022Comments
-
Martin Hollingsworth almost 2 years
The Determine Users Accessing a Shared Folder Using PowerShell question has a good answer. Continuing on from that How do you disconnect the users accessing the share using a powershell script.
There is a Windows command line utility called OpenFiles but I'd prefer a PowerShell / WMI solution.
-
tony roth about 14 yearsall user from the share or just drop a user?
-
MattB about 14 yearswhy the aversion to using a built in windows command? Either openfiles or
net files
would seem to suit your need without much hassle. -
Martin Hollingsworth about 14 yearsI have used OpenFiles in the meantime but because I want to be selective about which connections I disconnect, I end up using Select-String to try and parse the output of openfiles /query /v. I think my dodgy scripting skills make this a bit fragile and it would be easier for me if I was able to deal with the connections as Objects rather than passing the string.
-
-
jscott almost 13 yearsYou should mark this answer as "accepted". It is acceptable, encouraged even, to answer your own questions.