Determine Users Accessing a Shared Folder Using PowerShell
Solution 1
I came up with the following script:
$computer = "LocalHost"
$namespace = "root\CIMV2"
$userSessions = Get-WmiObject -class Win32_ServerConnection -computername $computer -namespace $namespace
if($userSessions -ne $null)
{
Write-Host "The following users are connected to your PC: "
foreach ($userSession in $userSessions)
{
$userDetails = [string]::Format("User {0} from machine {1} on share: {2}", $userSession.UserName, $userSession.ComputerName, $userSession.ShareName)
Write-Host $userDetails
}
Read-Host
}
The following articles were useful:
- http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/filesfolders/sharedfolders/
- http://www.computerperformance.co.uk/powershell/powershell_wmi_shares.htm
- http://www.codeproject.com/KB/cs/NetWorkSpy.aspx?msg=2384830
As always, if you can't find a way to do it in PowerShell, see if someone has done something similar in C#.
Solution 2
I've modified it a bit to show hostname instead of IP:
$computer = "LocalHost"
$namespace = "root\CIMV2"
$userSessions = Get-WmiObject -class Win32_ServerConnection -computername $computer -namespace $namespace
if($userSessions -ne $null)
{
Write-Host "The following users are connected to your PC: "
foreach ($userSession in $userSessions)
{
$ComputerName = [system.net.dns]::resolve($usersession.computername).hostname
$userDetails = [string]::Format("User {0} from machine {1} on share: {2}", $userSession.UserName, $ComputerName, $userSession.ShareName)
Write-Host $userDetails
}
Read-Host
}
Tangiest
I am a software developer who works mainly with the .Net framework (primarily C#, but also VB.Net and PowerShell). I have suffered greatly a lot of experience with SharePoint (2003, 2007, 2010, 2013, 2016 and SharePoint Online). I now develop mainly Azure and Microsoft 365 based solutions. You can check out my blog on programming and technology at tangiest.co.uk. Contact Details https://www.andyparkhill.co.uk/p/contact-me.html
Updated on June 05, 2022Comments
-
Tangiest almost 2 years
I need to determine the users/sessions accessing a shared folder on a Windows XP (SP2) machine using a PowerShell script (v 1.0). This is the information displayed using Computer Management | System Tools | Shared Folders | Sessions. Can anyone give me pointers on how to go about this?
I'm guessing it will require a WMI query, but my initial search online didn't reveal what the query details will be.
Thanks, MagicAndi