Asynchronous PowerShell Profile Loading

By | November 15, 2016

This script is meant to go in your PowerShell $PROFILE (\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1) file.

It loads the profile in a non blocking fashion allowing long running scripts like this quotation one to work and still enabling access to use PowerShell while it is being loaded in the background. Cross dependent scripts can’t be loaded using this as dependencies cannot be determined.  To add more startup items just add more {Start-Job -ScriptBlock {} -Name “StartUp#”} items before the timer section. This is mostly unlimited.

#Example quote script

$quoteScript = {
$test = Invoke-WebRequest http://www.quotationspage.com/random.php3
$what = $test.ParsedHtml.getElementsByTagName("dl")
$childNodes = $what[0].childnodes
$countme = 0
foreach($childNode in $childNodes){
    if($childNode.nodeName -eq "DT"){
        $quote += $childNode.innerText
    }

    if($childNode.nodeName -eq "DD"){
    #Match and remove - More  quotations *
        $quote += ($childNode.innerText -replace '- More quotations on:\s+\S+', '')
        $quote += "`n`n`n"
        $countme++
    }
    if($countme -gt 2){ break}
}
Write-Host "`n $quote" -ForegroundColor Cyan
}

#Non blocking timer object
Start-Job -ScriptBlock $quoteScript -Name "StartUp1"
$timer = New-Object System.Timers.Timer
$timer.Interval = 1000
$timer.AutoReset = $true
Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier "StartUp0" -Action {
    $jobs = Get-Job -Name "StartUp*"
    if($jobs.count -gt 1){
        foreach ($job in $jobs){
            if($job.State -ne "Running"){
                Receive-Job $job.Name
                Remove-Job $job.Name
            }

        }
    }
    else{
        $timer.stop()
        Unregister-Event "StartUp0"
        Remove-Job "StartUp0"
        Write-Host  "Asynchronous profile load completed" -ForegroundColor Green
    }
}
Write-Host "Asynchronous profile load starting ..." -ForegroundColor Yellow
$timer.Start()

Post Revisions:

This post has not been revised since publication.