3

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

Tangiest
  • 43,737
  • 24
  • 82
  • 113

2 Answers2

4

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:

As always, if you can't find a way to do it in PowerShell, see if someone has done something similar in C#.

Tangiest
  • 43,737
  • 24
  • 82
  • 113
  • 2
    I like the solution - just keep in mind for "interactive" use, `net session` is quicker. – Keith Hill Nov 25 '09 at 19:32
  • @MagicAndi: The existence of Read-Host causes the script to halt. What was your plan for this line? – Robin Sep 16 '14 at 09:57
  • Rob, to answer your question...the read-host at the end keeps the console window from automatically closing when this script is ran, so that you can see the output. This is only necessary when you are running the script from an explorer window by double-clicking it. Hopefully by now you have figured this out but for anyone else that might come across this question.....there you go. – Dimesio Jun 03 '15 at 20:59
1

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
}
shadowz1337
  • 710
  • 1
  • 8
  • 21