After extensive testing, I found out that the number referenced in %SESSIONNAME% is not the same number as the session id under Win32_Process.
However, I did find that the %TEMP% and %TMP% env variables contain the session id at the end of the path.
Example : C:\Documents and Settings\[username]\Local Settings\Temp\[session_id]
I'm not sure how solid this is, but it'll do for now unless you guys have a better idea to get the session id. Here is the revised EnumProcess function which supports Terminal Server sessions.
Code:
Function ProductSuite ($Product)
Dim $res, $x
Select
Case $Product = "None"
$x=0
Case $Product = "Small Business"
$x=1
Case $Product = "Enterprise"
$x=2
Case $Product = "BackOffice"
$x=4
Case $Product = "CommunicationServer"
$x=8
Case $Product = "Terminal Server"
$x=16
Case $Product = "Small Business (Restricted)"
$x=32
Case $Product = "Embedded NT"
$x=64
Case $Product = "DataCenter"
$x=128
Case $Product = "Single User Terminal Server"
$x=256
Case $Product = "Home Edition"
$x=512
Case $Product = "Blade Server"
$x=1024
Case 1
$res=MessageBox ("Invalid parameter used in function ProductSuite ($Product)",48)
EndSelect
$ProductSuite = $x & Val(@ProductSuite)
EndFunction
Function GetSessionID
Dim $sPath[]
$sPath = Split(%TEMP%, "\")
$GetSessionID = Trim($sPath[Ubound($sPath)])
EndFunction
Function EnumProcess($exe, optional $terminate, optional $Computer)
Dim $winmgmts, $ExecQuery, $Process, $id, $sessionid
Dim $GetObject
If NOT $computer $computer=@wksta EndIf
$winmgmts="winmgmts:{impersonationLevel=impersonate}!//$COMPUTER"
Select
Case Val($exe)>0
If ProductSuite("Terminal Server")
$sessionid = GetSessionID
$ExecQuery="select * from Win32_Process where ProcessId='$exe' and SessionId='$sessionid'"
Else
$ExecQuery="select * from Win32_Process where ProcessId='$exe'"
EndIf
$GetObject=GetObject($winmgmts).ExecQuery($ExecQuery)
For Each $Process in $GetObject
If $terminate $=$Process.Terminate EndIf
$EnumProcess = $Process.name
Next
$GetObject=''
Case VarType($exe)=8
If ProductSuite("Terminal Server")
$sessionid = GetSessionID
$ExecQuery="select * from Win32_Process where Name='$exe' and SessionId='$sessionid'"
Else
$ExecQuery="select * from Win32_Process where Name='$exe'"
EndIf
$GetObject=GetObject($winmgmts).ExecQuery($ExecQuery)
For Each $Process in $GetObject
If $terminate $=$Process.Terminate EndIf
$id=$Process.ProcessId
$EnumProcess = "$Id" + "|" + "$EnumProcess"
Next
$EnumProcess=Left($EnumProcess,Len($EnumProcess)-1)
$GetObject=''
Case 1
Exit 1
EndSelect
EndFunction