Introduction
PowerShell allows you to create multiple script instances using Start-Process and background jobs. This helps run tasks at the same time, making your script more efficient. Running long tasks can use a lot of memory and CPU, but by splitting tasks, you can manage them better.
Suppose we need to retrieve details from 10,000 SharePoint sites and update an SQL database table with this information. Fetching the complete list and library data from each site will take at least 10 minutes per site. This process is very time-consuming, and running such a lengthy PowerShell script would consume a lot of memory and likely result in an exception.
Here is a straightforward example of using Start-Process and scriptblock to execute tasks sequentially, ensuring one instance runs at a time.
Solution
Iterate through a loop of SharePoint sites to retrieve the details and send the required parameters as base64 string to the Start-Process cmdlet.
The result returned from Start-Process provides the process ID of the PowerShell session, which we can use to continuously monitor whether the task has been completed. Once it is completed, we can start executing the next site. This will ensure that only one new PowerShell instance is currently running.