Is there a way to get the TID (thread id) in powershell foreach-object -parallel?

Viewed 940
1 Answers

Unlike for the process ID ($PID), there is no automatic PowerShell variable reflecting the thread ID (as of PowerShell 7.2).

If getting the managed (as opposed to the native) thread ID is sufficient, you can use .NET APIs (System.Threading.Thread.CurrentThread):

1..2 | % -Parallel { [System.Threading.Thread]::CurrentThread.ManagedThreadId }

To get the native thread ID you need platform-specific solutions via P/Invoke; e.g., for Windows, using the GetCurrentThreadId() WinAPI function:

# For Windows
Add-Type -Name WinApi -Namespace demo -MemberDefinition @'
  [DllImport("Kernel32.dll")]
  public static extern uint GetCurrentThreadId();
'@

1..2 | % -Parallel { [demo.WinApi]::GetCurrentThreadId() }
Related