Application Scenarios
Multithreading is useful when you need to batch-process some tasks, and it is also more conducive to leveraging the capabilities of existing computers. All major development languages support multithreading.
By default, PowerShell, as a scripting language, does not support multithreaded operations, although there are so-called background tasks, but in fact it is quite cumbersome to control.
Solution Solutions
I like PowerShell very much, so I wrote a custom module to realize the multi-threaded function. The module is written in C # and the source code can be accessed at the following address
Https://github.com/chenxizhang/MultiThreadTaskRunner
At the same time, the module has been packaged and released into Microsoft's official PowerShell Gallery
https://www.powershellgallery.com/packages/MultiThreadTaskRunner/1.0
How to use
To use this module, you first need to install it (please open POWERSEHLL as an administrator)
Install-Module -Name MultiThreadTaskRunner
Next, prepare a script block for testing
$script ={
Param ($obj);
Write-host $obj
}
Note that this is only implemented with the simplest code, and the output data is based on one parameter passed in.
The third step, you can quickly use the
New-multitaskjob–source 1..100–block $script –threadcount 10
This command means, with 10 parallel threads, to process the 100 numbers passed in, in fact each thread assigns a number of 10, and then executes it using the previously defined script block
Note that you can see that the results of the output at this time are not in the order of 1 to 100, which proves that the numbers are actually handled by different threads.
Publish a PowerShell module that supports multithreading--multithreadtaskrunner