About Me · Send mail to the author(s) E-mail · Twitter

At GROSSWEBER we practice what we preach. We offer trainings for modern software technologies like Behavior Driven Development, Clean Code and Git. Our staff is fluent in a variety of languages, including English.

Feed Icon


Open Source Projects


Blogs of friends

Now playing [?]

Error retrieving information from external service.

Enumerating Foreign Interactive Sessions in Powershell

Posted in PowerShell at Friday, 13 April 2007 17:40 W. Europe Daylight Time

A reader asked if it is possible to get all interactive sessions not created by the current user (i.e. the Administrator) in Powershell. Since I had done something similar in my Terminal Server logon script some time ago I thought this would be pretty easy to achieve. Again, I'm heavily relying on WMI. Yet, handling the "flat" (in an OO sense) WMI objects mostly containing string properties doesn't seem right. Here's what I came up with:

# Prints the number of interactive sessions not created by the current user.

$CurrentUserFragment = "*Domain=`"" + $Env:UserDomain.Trim() + "`",Name=`"" + $Env:Username.Trim() + "`""

# Get all interactive sessions (including Terminal Server sessions).
$InteractiveSessions = Get-WmiObject Win32_LogonSession | Where-Object {
    $_.LogonType -eq 2 -or $_.LogonType -eq 10

$ForeignSessions = 0
foreach($Session in $InteractiveSessions) {
    $SessionIdFragment = "*`"" + $Session.LogonId + "`""
    # Test if the session is established by the current user.
    $ForeignSession = Get-WmiObject Win32_LoggedOnUser | Where-Object {
        $_.Antecedent -inotlike $CurrentUserFragment -and $_.Dependent -ilike $SessionIdFragment
    } | Measure-Object
    $ForeignSessions += $ForeignSession.Count

Write-Host $ForeignSessions "Foreign Interactive Session(s)"

This command basically mimics this UNIX command supplied by the reader¹:

who | grep -V "root" | wc -l

The Powershell script is not as concise as I would like it to be and presumably could be optimized. My quick hack should be wrapped in a Cmdlet if you plan to use it in a professional environment.

¹ I have no idea if the script works because I didn't test it. 

Now Playing [?]: Thievery CorporationThe Cosmic GameDoors of perception (feat. Gunjan)

All comments require the approval of the site owner before being displayed.
(will show your gravatar icon)
[Captcha]Enter the code shown (prevents robots):

Live Comment Preview