7

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.

3
  • all user from the share or just drop a user?
    – tony roth
    Jun 10, 2010 at 4:29
  • why the aversion to using a built in windows command? Either openfiles or net files would seem to suit your need without much hassle.
    – MattB
    Jun 10, 2010 at 15:08
  • 1
    I 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. Jun 10, 2010 at 22:27

2 Answers 2

5

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 `"$_`"}
1
  • 2
    You should mark this answer as "accepted". It is acceptable, encouraged even, to answer your own questions.
    – jscott
    Aug 30, 2011 at 11:41
0

Openfiles works good for me. Although you don't need to do all that saving of openfiles /query and then disconnect them one-by-one as the "*" wildcard can be used to disconnect all open sessions you can do something like:

openfiles /Disconnect /ID *

Which will terminate all open connections

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .