Skip to content

Instantly share code, notes, and snippets.

@gislig
Created May 15, 2018 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gislig/1a809f6c5fb56ade176b46e6b8c8167a to your computer and use it in GitHub Desktop.
Save gislig/1a809f6c5fb56ade176b46e6b8c8167a to your computer and use it in GitHub Desktop.
# ------------------------------- #
# 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