powershellforeach-object

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


Just wondering if I could get like a $TID for thread id, just like a $PID or process id, with foreach-object -parallel in powershell 7 or pwsh (https://github.com/PowerShell/PowerShell#-powershell). I can run this and see a bunch of threads with a TID column in sysinternals procexp (https://learn.microsoft.com/en-us/sysinternals/downloads/process-explorer), in the pwsh.exe properties, Threads tab.

 1..20 | foreach-object -Parallel { start-sleep (5*$_) } -ThrottleLimit 20

enter image description here


Solution

  • 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() }