Skip to content

Instantly share code, notes, and snippets.

@asears
Forked from JeffMill/WordAutomation-Threaded.ps1
Created November 2, 2024 12:55
Show Gist options
  • Save asears/c31aad847247dddd51d3cd9f1e74d4d3 to your computer and use it in GitHub Desktop.
Save asears/c31aad847247dddd51d3cd9f1e74d4d3 to your computer and use it in GitHub Desktop.
Automate word (threaded)
$ScriptBlock =
{
Param([int]$RunNumber)
$filename = Join-Path ([IO.Path]::GetTempPath()) "powershell-$RunNumber.doc"
'Opening Word ...'
$oWord = New-Object -Com Word.Application
$oWord.Visible = $true
$oDoc = $oWord.Documents.Add()
$oPara1 = $oDoc.Paragraphs.Add()
$oPara1.Range.Style = 'Heading 1'
$oPara1.Range.Text = 'Insert a Paragraph with PowerShell'
$oPara1.Range.InsertParagraphAfter()
$oPara2 = $oDoc.Paragraphs.Add()
$oPara2.Range.Text = 'Microsoft Word automation is simple with PowerShell'
$oPara2.Range.InsertParagraphAfter()
for ($line = 1; $line -le 50; $line++) {
Start-Sleep -Seconds 5
"Adding line $line..."
$oPara = $oDoc.Paragraphs.Add()
$oPara.Range.Text = "Line " + $line
$oPara.Range.InsertParagraphAfter()
}
"Saving as $filename ..."
$oDoc.SaveAs($filename)
'Closing ...'
$oDoc.Close()
$oWord.Quit([ref]$false)
$RunResult = New-Object PSObject -Property @{
RunNumber = $RunNumber
}
return $RunResult
}
Write-Host 'Creating runspace pool.'
$MaxThreads = 4
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, $MaxThreads)
$RunspacePool.Open()
$Jobs = @()
1..20 | ForEach-Object {
$Job = [PowerShell]::Create().AddScript($ScriptBlock).AddArgument($_)
$job.RunspacePool = $RunspacePool
$Jobs += New-Object PSObject -Property @{
RunNum = $_
Pipe = $Job
Result = $Job.BeginInvoke()
}
}
Write-Host 'Waiting' -NoNewline
Do {
Write-Host '.' -NoNewline
Start-Sleep -Seconds 1
} While ($Jobs.Result.IsCompleted -contains $false)
Write-Host 'All jobs completed!'
$Results = @()
ForEach ($Job in $Jobs) {
$Results += $Job.Pipe.EndInvoke($Job.Result)
}
$Results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment