-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathGet-NetSession.ps1
More file actions
263 lines (234 loc) · 10.4 KB
/
Get-NetSession.ps1
File metadata and controls
263 lines (234 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
Function Get-NetSession {
<#
.SYNOPSIS
Queries the remote system for all net sessions
.DESCRIPTION
Queries the remote system for all net sessions
.PARAMETER Computername
Computer to query for net sessions
.PARAMETER Username
Specifies a user to look for in the net sessions
.PARAMETER IncludeSelf
Includes the current user session used to run this command
.NOTES
Name: Get-NetSession
Author: Boe Prox
Version History:
1.1 //Boe Prox - 1 August 2016
- Added IncludeSelf parameter to include displaying the session created from command otherwise
this data is not presented
- Bug fixes
1.0 //Boe Prox - 28 July 2016
- Initial build
.EXAMPLE
Get-NetSession -Computername Server1
Computername : Server1
SourceComputer : Workstation1
SourceIPAddress : 192.168.2.56
Username : bobsmith
SessionTime : 0
IdleTime : 0
Computername : Server1
SourceComputer : Workstation2
SourceIPAddress : 192.168.2.110
Username : joeuser
SessionTime : 348607
IdleTime : 345850
Description
-----------
Returns all net sessions on Server1
#>
[cmdletbinding()]
Param (
[parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[string[]]$Computername,
[parameter()]
[string]$Username = '',
[parameter()]
[switch]$IncludeSelf
)
Begin {
If ($PSBoundParameters.ContainsKey('Debug')) {
$DebugPreference = 'Continue'
}
If (-NOT $PSBoundParameters.ContainsKey('IncludeSelf')) {
$Hostname = "$($env:COMPUTERNAME).$($env:USERDNSDOMAIN)"
Write-Verbose "Excluding $Hostname and $($env:USERNAME)"
}
#region Reflection
Try {
[void][Net.Session]
}
Catch {
Write-Verbose "Building pinvoke via reflection"
#region Module Builder
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('NetSession')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) # Only run in memory
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('NetSessionModule', $False)
#endregion Module Builder
#region Custom Attribute Builder
$ctor = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructor(@([System.Runtime.InteropServices.UnmanagedType]))
$CustomAttribute = [System.Runtime.InteropServices.UnmanagedType]::LPWStr
$CustomAttributeBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder -ArgumentList $ctor, $CustomAttribute
#endregion Custom Attribute Builder
#region Struct
#region SESSION_INFO_10
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SESSION_INFO_10', $Attributes, [System.ValueType], 8, 0x0)
$Field = $STRUCT_TypeBuilder.DefineField('OriginatingHost', [string], 'Public')
$Field.SetCustomAttribute($CustomAttributeBuilder)
$Field = $STRUCT_TypeBuilder.DefineField('DomainUser', [string], 'Public')
$Field.SetCustomAttribute($CustomAttributeBuilder)
[void]$STRUCT_TypeBuilder.DefineField('SessionTime', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.DefineField('IdleTime', [uint32], 'Public')
[void]$STRUCT_TypeBuilder.CreateType()
#endregion SESSION_INFO_10
#endregion Struct
$TypeBuilder = $ModuleBuilder.DefineType('Net.Session', 'Public, Class')
#region Methods
#region NetSessionEnum Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
'NetSessionEnum', #Method Name
[Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
[int32], #Method Return Type
[Type[]] @(
[string],
[string],
[string],
[int32],
[intptr].MakeByRefType(),
[int],
[int32].MakeByRefType(),
[int32].MakeByRefType(),
[int32].MakeByRefType()
) #Method Parameters
)
#Define first three parameters with custom attributes
1..3 | ForEach {
$Parameter = $PInvokeMethod.DefineParameter(
$_,
[System.Reflection.ParameterAttributes]::In,
$Null
)
$Parameter.SetCustomAttribute(
$CustomAttributeBuilder
)
}
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
[Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
[Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
[Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
[Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)
$FieldValueArray = [Object[]] @(
'NetSessionEnum', #CASE SENSITIVE!!
$True,
$True,
$True
)
$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
$DllImportConstructor,
@('Netapi32.dll'),
$FieldArray,
$FieldValueArray
)
$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion NetSessionEnum Method
#region NetApiBufferFree Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
'NetApiBufferFree', #Method Name
[Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
[int], #Method Return Type
[Type[]] @(
[intptr]
) #Method Parameters
)
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
[Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
[Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
[Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
[Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
)
$FieldValueArray = [Object[]] @(
'NetApiBufferFree', #CASE SENSITIVE!!
$True,
$True,
$True
)
$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
$DllImportConstructor,
@('Netapi32.dll'),
$FieldArray,
$FieldValueArray
)
$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#endregion NetApiBufferFree Method
#endregion Methods
[void]$TypeBuilder.CreateType()
}
#endregion Reflection
}
Process {
ForEach ($Computer in $Computername) {
Write-Verbose "Scanning $Computer"
$SessionInfo10 = New-Object -TypeName SESSION_INFO_10
$SessionInfo10Size = [System.Runtime.InteropServices.Marshal]::SizeOf($SessionInfo10)
$Buffer = [IntPtr]::Zero
[int32]$EntriesRead = 0
[int32]$TotalEntries = 0
[int32]$ResumeHandle = 0
$Return = [Net.Session]::NetSessionEnum(
$Computer,
"",
$Username,
10,
[ref]$Buffer,
-1,
[ref]$EntriesRead,
[ref]$TotalEntries,
[ref]$ResumeHandle
)
$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
If ([System.IntPtr]::Size -eq 4) {
$BufferOffset = $Buffer.ToInt32()
}
Else {
$BufferOffset = $Buffer.ToInt64()
}
For ($Count = 0; ($Count -lt $EntriesRead); $Count++){
$NewBuffer = New-Object System.Intptr -ArgumentList $BufferOffset
$Info = [System.Runtime.Interopservices.Marshal]::PtrToStructure($NewBuffer,[type]$SessionInfo10.GetType())
$Info | ForEach {
$IP = $_.OriginatingHost.Trim('\\')
Try {
$ResolvedName = [Net.DNS]::GetHostByAddress($IP).HostName
}
Catch {
$ResolvedName = 'N/A'
}
$Object = [pscustomobject]@{
Computername = $Computer
SourceComputer = $ResolvedName
SourceIPAddress = $IP
Username = $_.DomainUser
SessionTime = $_.SessionTime
IdleTime = $_.IdleTime
}
$Object.pstypenames.insert(0,'Net.SessionInformation')
If (($PSBoundParameters.ContainsKey('IncludeSelf'))) {
$Object
}
ElseIf (-NOT ((($ResolvedName -eq $Hostname) -OR ($IP -eq $env:COMPUTERNAME)) -AND ($_.DomainUser -eq $env:USERNAME))) {
$Object
}
}
$BufferOffset = $BufferOffset + $SessionInfo10Size
}
[void][Net.Session]::NetApiBufferFree($Buffer)
}
}
End {}
}