Skip to content

Instantly share code, notes, and snippets.

@jborean93
Last active May 3, 2019 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jborean93/d4359898b1c378c8828aa2b817c0ad68 to your computer and use it in GitHub Desktop.
Save jborean93/d4359898b1c378c8828aa2b817c0ad68 to your computer and use it in GitHub Desktop.
Get process session, station, and desktop
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace ProcessInfo
{
public class NativeMethods
{
[DllImport("User32.dll", SetLastError = true)]
public static extern bool CloseDesktop(
IntPtr hDesktop);
[DllImport("Kernel32.dll")]
public static extern UInt32 GetCurrentThreadId();
[DllImport("User32.dll", SetLastError = true)]
public static extern IntPtr GetProcessWindowStation();
[DllImport("User32.dll", SetLastError = true)]
public static extern IntPtr GetThreadDesktop(
UInt32 dwThreadId);
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool GetUserObjectInformationW(
IntPtr hObject,
int nIndex,
IntPtr pvInfo,
UInt32 nLength,
ref UInt32 lpnLengthNeeded);
}
}
'@
Function Get-UserObjectName {
[CmdletBinding()]
Param([IntPtr]$Handle)
$ptr_length = 0
[ProcessInfo.NativeMethods]::GetUserObjectInformationW($Handle, 2, [IntPtr]::Zero, $ptr_length,
[Ref]$ptr_length) > $null
$name_ptr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($ptr_length)
try {
$res = [ProcessInfo.NativeMethods]::GetUserObjectInformationW($Handle, 2, $name_ptr, $ptr_length,
[Ref]$ptr_length)
if (-not $res) {
$err_code = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
$exp = New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList $err_code
Write-Error -Message ("Failed to get object name: {0} (Win32 ErrorCode {1} - 0x{1:X8})" -f $exp.Message, $err_code)
return
}
[System.Runtime.InteropServices.Marshal]::PtrToStringUni($name_ptr)
} finally {
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($name_ptr)
}
}
Function Get-ProcessSessionStationAndDesktop {
[CmdletBinding()]
Param ()
$station_ptr = [ProcessInfo.NativeMethods]::GetProcessWindowStation()
$station_name = Get-UserObjectName -Handle $station_ptr
$desktop_ptr = [ProcessInfo.NativeMethods]::GetThreadDesktop([ProcessInfo.NativeMethods]::GetCurrentThreadId())
try {
$desktop_name = Get-UserObjectName -Handle $desktop_ptr
} finally {
[ProcessInfo.NativeMethods]::CloseDesktop($desktop_ptr) > $null
}
[PSCustomObject]@{
Session = ([System.Diagnostics.Process]::GetCurrentProcess()).SessionId
Station = $station_name
Desktop = $desktop_name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment