Instantly share code, notes, and snippets.

Embed
What would you like to do?
# ------------------------------- #
# Powershell Parallel Processing
#
# Written by Gísli Guðmundsson
# 2018
# ------------------------------- #
$Files = "C:\Temp\file1.txt","C:\Temp\file2.txt","C:\Temp\file3.txt","C:\Temp\file4.txt"
#Loop through the files Array
foreach($Filename in $files){
#Check if the whofirst file exists, if so delete it
if(Test-Path $WhoFirst){ Remove-Item $WhoFirst }
#Scriptblock interface where it runs basically more than once.
$ScriptBlock = {
#Get parameters and assign to the scriptblock, this may include external data as we do in this scenario
param($Filename)
function newfile($Filename) {
#Remove the files
Remove-Item $Filename
#Do a random loop
$RandomLoop = Get-Random -Minimum 1 -Maximum 10
#Loop through random loop
for($i = 0;$i -lt $RandomLoop;$i++){
#Do some calculations to slow down the process
$Random1 = Get-Random -Minimum 1 -Maximum 1000000000000000
$Random2 = Get-Random -Minimum 1 -Maximum 1000000000000000
$Random = [math]::Sqrt($Random)/$Random1/$Random2*$Random1*[math]::PI
#Sleep for few seconds
$RandomSleep = Get-Random -Minimum 1 -Maximum 3
Start-Sleep -s $RandomSleep
}
$Date = Get-Date
$Output = "$Date`n`t$Random"
#Write the output to a file
$Output | Out-File $Filename
}
#Run the function, send the parameter through, which is the filename
newfile -Filename $Filename
$WhoFirst = "c:\temp\whofirst.txt"
$Filename | Out-File $WhoFirst -Append
}
#Run the scriptblock with arguments
Start-Job $ScriptBlock -ArgumentList $Filename
}
#Display the jobs running
While (Get-Job -State "Running") { Start-Sleep 2 }
#Remove all the finished jobs
Remove-Job *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment