Last active
December 14, 2022 17:44
-
-
Save tresf/b0d3d06728236fe988384a8e14c0d019 to your computer and use it in GitHub Desktop.
PowerShell: Get active windows login sessions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Adopted from: https://www.reddit.com/r/PowerShell/comments/306mcn/wtsenumeratesessions/ | |
# Original Author: u/geostude | |
$_WTSMyStruct_Def = @' | |
namespace mystruct { | |
using System; | |
using System.Runtime.InteropServices; | |
[StructLayout(LayoutKind.Sequential)] | |
public struct WTS_SESSION_INFO { | |
public Int32 SessionID; | |
[MarshalAs(UnmanagedType.LPStr)] | |
public String pWinStationName; | |
public WTS_CONNECTSTATE_CLASS State; | |
} | |
public enum WTS_CONNECTSTATE_CLASS { WTSActive, WTSConnected, WTSConnectQuery, WTSShadow, WTSDisconnected, WTSIdle, WTSListen, WTSReset, WTSDown, WTSInit } | |
} | |
'@ | |
$_WTSEnumerateSessions_Def = @' | |
[DllImport("wtsapi32.dll", SetLastError=true)] | |
public static extern int WTSEnumerateSessions(System.IntPtr hServer, int Reserved, int Version, ref System.IntPtr ppSessionInfo, ref int pCount); | |
'@ | |
$_WTSOpenServer_Def = @' | |
[DllImport("wtsapi32.dll", SetLastError=true)] | |
public static extern IntPtr WTSOpenServer(string pServerName); | |
'@ | |
Add-Type $_WTSMyStruct_Def | |
$WTSEnumerateSessions = Add-Type -MemberDefinition $_WTSEnumerateSessions_Def -Name PSWTSEnumerateSessions -Namespace GetLoggedOnUsers -PassThru | |
$WTSOpenServer = Add-Type -MemberDefinition $_WTSOpenServer_Def -Name PSWTSOpenServer -Namespace GetLoggedOnUsers -PassThru | |
[long]$count = 0 | |
[long]$ppSessionInfo = 0 | |
# Defaults to current computer; Change $env:computername to target computer | |
$server = $WTSOpenServer::WTSOpenServer($env:computername) | |
[long]$sessionCount = $WTSEnumerateSessions::WTSEnumerateSessions($server,0,1,[ref]$ppSessionInfo,[ref]$count) | |
$dataSize = [system.runtime.interopservices.marshal]::SizeOf([System.Type][mystruct.WTS_SESSION_INFO]) | |
if ($sessionCount -ne 0){ | |
for ($i = 0; $i -lt $count; $i++){ | |
$element = [system.runtime.interopservices.marshal]::PtrToStructure($ppSessionInfo + ($dataSize * $i),[System.type][mystruct.WTS_SESSION_INFO]) | |
$element | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment