Cold Starting and/or Hydrating Your Applications To Improve Their Startup Times

by Jeremy Saunders on June 27, 2023

In the End User Computing (EUC) space we know that after the first time the application starts post reboot, the next time is faster. The first startup is referred to as a cold startup and all subsequent runs are warm startups. The first time the application starts, components of the application, such as the EXEs (executables) and DLLs (dynamic link libraries) need to be loaded from disk, which can delay the startup time. All subsequent runs will then read the data from the file system cache, which is memory managed by the Operating System.

Hydrate and Cold Start your applications

The way we prepare a system for a user is to cold start (pre-launch) the applications when the system starts. We do this by starting and then terminating each process, such as winword.exe.

Wait…what? This seems a bit ugly and sounds like it can get messy. You bet! There are challenges with this method, as starting and terminating a process may…

  • Not deal with sub processes, or other processes that it may spawn. This is extremely important, otherwise you may leave orphaned processes running under the SYSTEM (or service) account which could cause application issues, lock licenses, etc.
  • Not leave sufficient time between starting and terminating so it loads properly.
  • Not start the application to a point that is loads enough components into file system cache before terminating.
  • Unnecessarily check out or lock a license.
  • Cause a process/application to crash, creating Event Viewer errors, and/or prompt the user with a “recovery” option when it starts the next time.

So whilst cold starting is a great idea in theory, starting and terminating the process is not always a good fit for every application. From my experience you need to know your apps well enough and do a lot of testing to get this right, or what you are doing will be hit and miss, and may actually create unnecessary incidents. As I’ve been using this process since 2016 I made several errors along the way, which I learnt from, as per the list above.

Then in 2020 I took a leaf out of my friend Matthias Schlimm’s book and added hydration to my process. This uses a binary read to open the specified file, reads its contents into memory using a byte array, and then closes the file. You’re not actually starting the application, which can be a cleaner way of achieving a “cold start”. There are limitations to this method too. To avoid reading in every file under a folder structure, which is unnecessary, we just specify file extensions, such as .exe and .dll. This typically covers off enough for most apps. From my experience I also add .cab, but you are free to set whatever is required to suite your needs.

Whilst the initial reason I wrote this was to speed up launching of Citrix published apps (and perceived logon times) after an RDSH or VDI Session Host has restarted, it can be used for Full Desktop sessions, VMware Horizon, Azure Virtual Desktops, and any other Server and Desktop implementation; whether they be virtual or physical.

Furthermore, in a Citrix Provisioning Services (PVS) environment, the Target Devices will only stream down whatever is needed for the Windows boot process to complete, and anything that runs in the background before the user logs on. So as a user logs on and starts their apps, these “application” files are initially streaming from the PVS Server, which will appear as slower than “normal” to the user. So by starting the apps or hydrating the folder structures, we are not only indirectly cold starting them, but also streaming the files down to the PVS Target Device.

This PowerShell script and process provides both methods:

  • Cold Start, where it start the process and then terminate it based on the parameters you set, including a wait time and termination of sub processes that may remain open after the main process has terminated.
  • Hydrate, where does a binary read of all files of certain type(s) in a folder structure.

The biggest challenge to both these methods is that it can add considerable time to the post computer startup process if you have many apps or folder structures that you want to process. We want to avoid a user logging in whilst this is running. So I’m doing this all in PowerShell runspaces to make it multithreaded in an attempt to execute and queue as many tasks in parallel as possible.

In a Citrix environment I tend to set the Delivery Group “SettlementPeriodBeforeUse” property to 15 minutes to allow time for this script to complete its processing before the Session Host is selected to host a new session.

The script references XML file(s) to get the information for each process or folder including the method used to start/open it.

Here is an example of the XML contents.

<configuration>
	<Processes>
		<Process Name="Microsoft Word">
			<Path>%ProgramFiles(x86)%\Microsoft Office\Office15</Path>
			<Executable>winword.exe</Executable>
			<Read>False</Read>
			<CommandLineContains></CommandLineContains>
			<ExtraProcessesToTerminate></ExtraProcessesToTerminate>
			<TerminateAfterInSeconds>9</TerminateAfterInSeconds>
		</Process>
		<Process Name="Microsoft Excel">
			<Path>%ProgramFiles(x86)%\Microsoft Office\Office15</Path>
			<Executable>excel.exe</Executable>
			<Read>False</Read>
			<CommandLineContains></CommandLineContains>
			<ExtraProcessesToTerminate></ExtraProcessesToTerminate>
			<TerminateAfterInSeconds>9</TerminateAfterInSeconds>
		</Process>
	</Processes>
	<Folders>
		<Folder Path="%ProgramFiles%\ArcGIS">
			<Extensions>*.exe,*.dll</Extensions>
			<Recurse>True</Recurse>
		</Folder>
		<Folder Path="%ProgramFiles(x86)%\ArcGIS">
			<Extensions>*.exe,*.dll</Extensions>
			<Recurse>True</Recurse>
		</Folder>
		<Folder Path="%ProgramFiles(x86)%\TIBCO\Spotfire">
			<Extensions>*.exe,*.dll</Extensions>
			<Recurse>True</Recurse>
		</Folder>
	</Folders>
</configuration>

Whilst you can use the full path, the XML paths will also accept the following environment variables:

  • %ProgramFiles(x86)%
  • %ProgramFiles%
  • %ProgramData%
  • %SystemDrive%
  • %SystemRoot%

In the example provided it’s setup to cold start Word and Excel, and will also hydrate all .exe, .dll and .cab files from the “C:\Program Files\ArcGIS”, “C:\Program Files (x86)\ArcGIS”, and  “C:\Program Files (x86)\TIBCO\Spotfire” folder structures.

It will process multiple XML files by enumerating all XML files in the same path as the script that start with the same name as the script. i.e. It will search for all files that start with ProcessesToStart* and have an extension of .xml. Therefore you can have a base XML file and layer others in for different images/use cases, which is what I do.

Each section is optional. You use Processes section when you want to cold start, and Folders section when you want to hydrate. Or you can use both together as per the example.

I recommend that at the very minimum you should ensure that all the main, most used, and “heaviest” applications are taken care of by these methods. You will be amazed at how much time this can trim from the application launch times. And if using Published Applications, the perception will be an improvement of the logon times. Therefore you’re enhancing the user experience.

For the Processes section each Process has a…

  • Name: The application name.
  • Path: The path to the executable. Supports standard environment variables.
  • Executable: The executable you want to cold start, or open and read.
  • Read: Set to False to start and terminate the process. Setting it to True to will perform a binary read only. I rarely set this to true, but as I use the Folder (hydration) elements for the binary reads. I simply added this here as an option you can use.
  • CommandLineContains: Can be left blank, or may contain part or all of the command line so that the process termination only targets a specific process if multiple processes with the same name are running. This is typically not used for this process, but is an option I added that you can use.
  • ExtraProcessesToTerminate: A comma separated list of any extra processes to terminate as sometimes an application can start/spawn other processes that don’t close when the main process terminates.
  • TerminateAfterInSeconds: Tells the script how many seconds to wait until terminating the process. If left blank, it will default to 1. A whole number must be used, or it will default to Ensure you give the process enough time to fully start.

For the Folders section each Folder has a…

  • Path: The path to the files you want to open and read. Supports standard environment variables.
  • Extensions: The extensions of the files you want to open and read.
  • Recurse: Set to True to process all subfolders.

For the hydration process we use the native .NET [System.IO.File]::ReadAllBytes(String) method to open a binary file, read the contents into a byte array, and then close the file, instead of the Get-Content cmdlet. The .NET methods tend to consume less memory and are more efficient/faster. Get-Content -Encoding Byte is traditionally slow, but using the ReadCount parameter set to 0 provides an interesting comparison. To understand what I’m referring to try out these two reads. Change the $file variable to reference a similar executable on your system.

$file = "C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE"
$sw = [Diagnostics.Stopwatch]::StartNew()
[Byte[]]$Bytes = [System.IO.File]::ReadAllBytes($file)
[Int]$ByteCount = $Bytes.Count
$ByteCount
$sw.Stop()
$sw.Elapsed
$file = "C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE"
$sw = [Diagnostics.Stopwatch]::StartNew()
[Byte[]]$Bytes = Get-Content "$file" -Encoding Byte -ReadCount 0
[Int]$ByteCount = $Bytes.Count
$ByteCount
$sw.Stop()
$sw.Elapsed

An old 2014 article from Shay Levy #PSTip Reading file content as a byte array was interesting at the time. But over the years your speed may vary with different versions of .NET and PowerShell. There is no right or wrong answer here. If you get a more efficient outcome using the Get-Content cmdlet, change the script to suite your needs, by swapping around the $scriptBlockRead and $scriptBlockRead2 variables in the PowerShell script.

I’ve never had a file locking issue, but if you experience one, changing the code to Reading a file without locking it seems rather simple to implement.

I tend to run this script from a Scheduled Task at System Startup, but you can also run it as a Computer Startup Script. The choice is yours.

References:

Here is the full Processes To Start (272 downloads)  in the in the form of a zip file, which includes the PowerShell script and XML file.

<#
  This script will either cold start or hydrate applications by loading them into file system
  cache after a Session Host (RDS or VDI) has started.

  - Cold Start = It starts and then terminates each application.
  - Hydrate = Does a binary read of all files of certain type(s) in a folder structure.

  The script uses PowerShell runspaces for multithreading to execute tasks in parallel.

  The script references XML file(s) to get the information for each process or folder including
  the method used to start/open it where it will either:
    1) Start the process and then terminate it based on the parameters you set, including
       a wait time and termination of sub processes that may remain open.
    OR
    2) Use a binary read to open the file, reads its contents into memory, and then close it.

  If processing certain file type(s) in a folder structure, the script references XML file(s)
  to get the information for each folder and file type(s) to read. It then uses a binary read
  to open the file, reads its contents into memory, and then close it.

  It will process multiple XML files by enumerating all XML files in the same path as the
  script that start with the same name as the script. i.e. It will search for all files that
  start wih ProcessesToStart* and have an extension of .xml. Therefore you can have a base
  XML file and layer others in for different images.

  This script will typically run from a Scheduled Task at System Startup to start each app
  (process), such as winword.exe, etc, which loads the executable and libraries into memory
  and file system cache, and then terminates each process.

  This significantly speeds up launching of the published apps (and logon times) after a
  Session Host has started.

  References:
  - https://web.archive.org/web/20201031213729/http://geekswithblogs.net:80/akraus1/archive/2015/08/25/166493.aspx
  - https://eucweb.com/kba/281219084515-2

  IMPORTANT NOTES:
  - Even though it uses PowerShell runspaces so it's multithreaded and optimised, the more
    processes and/or folder structures you add, the longer the script will take to run at
    startup. You must be aware of this and in a Citrix environment you may want to adjust
    the Delivery Group setting "SettlementPeriodBeforeUse" accordingly to allow time for this
    script to complete its processing before the Session Host can be selected to host a new
    session.
  - If starting and terminating the process, you also need to take into account the following:
    - "Terminate After In Seconds" to ensure you give the process enough time to fully start.
    - "Extra Processes To Terminate" that spawn from the initial process. This is extremely
      important, otherwise you may leave orphaned processes running under the SYSTEM account
      which could cause application issues, lock licenses, etc.
  - I recommend adding all published applications, or in the case of a published desktop,
    only the main applications used.
  - If you use this process to cold start Microsoft Excel, PowerPoint, Outlook, Word, etc,
    there will be zero byte CVR (Cockpit Voice Recorder) files created in the %TEMP% folder.
    The .CVR extension is a type of file that is created by Microsoft Windows programs when
    they crash. It is used to record and analyse information relating to the crash. In this
    case the CVR files can be ignored, as we are purposely "crashing" the application by
    terminating the process.

  An example of the contents of the XML file:

  <?xml version="1.0" encoding="utf-8"?>
  <configuration>
	<Processes>
		<Process Name="Microsoft Word">
			<Path>%ProgramFiles(x86)%\Microsoft Office\Office15</Path>
			<Executable>winword.exe</Executable>
			<Read>True</Read>
			<CommandLineContains></CommandLineContains>
			<ExtraProcessesToTerminate></ExtraProcessesToTerminate>
			<TerminateAfterInSeconds>9</TerminateAfterInSeconds>
		</Process>
		<Process Name="Microsoft Excel">
			<Path>%ProgramFiles(x86)%\Microsoft Office\Office15</Path>
			<Executable>excel.exe</Executable>
			<Read>True</Read>
			<CommandLineContains></CommandLineContains>
			<ExtraProcessesToTerminate></ExtraProcessesToTerminate>
			<TerminateAfterInSeconds>9</TerminateAfterInSeconds>
		</Process>
	</Processes>
	<Folders>
		<Folder Path="%ProgramFiles%">
			<Extensions>*.exe,*.dll,*.cab</Extensions>
			<Recurse>True</Recurse>
		</Folder>
		<Folder Path="%ProgramFiles(x86)%">
			<Extensions>*.exe,*.dll,*.cab</Extensions>
			<Recurse>True</Recurse>
		</Folder>
	</Folders>
  </configuration>

  Where for the Processes section each Process has a...
    Name = The application name
    Path = The path to the executable
    Executable = The executable you want to cold start
    Read = Set to True to process the executable as a binary read, or False to start and
       terminate the process.
    CommandLineContains = Can be left blank, or may contain part or all of the command
      line so that the process termination only targets a specific process if multiple
      processes with the same name are running. This is typically not used for this
      process, but is an option I added.
    ExtraProcessesToTerminate = A comma separated list of any extra processes to terminate
      as sometimes an application can start/spawn other processes.
    TerminateAfterInSeconds = Tells the script how many seconds to wait until terminating
      the process. If left blank, it will default to 1. A whole number must be used, or it
      will default to 1.

  Where for the Folders section each Folder has a...
    Path = The path to the files you want to open and read.
    Extensions = The extensions of the files you want to open and read.
    Recurse = Set to True to process all subfolders.

  Script Name: ProcessesToStart.ps1
  Release 2.3
  Written by Jeremy Saunders (jeremy@jhouseconsulting.com) 1st October 2016
  Modified by Jeremy Saunders (jeremy@jhouseconsulting.com) 17th September 2020

#>

#-------------------------------------------------------------

# Set Powershell Compatibility Mode
Set-StrictMode -Version 2.0

# Enable verbose, warning and error mode
$VerbosePreference = 'Continue'
$WarningPreference = 'Continue'
$ErrorPreference = 'Continue'

$StartDTM = (Get-Date)

#-------------------------------------------------------------

# Get the TEMP path
$logPath = [System.IO.Path]::GetTempPath()
$logPath = $logPath.Substring(0,$logPath.Length-1)

$ScriptName = [System.IO.Path]::GetFilenameWithoutExtension($MyInvocation.MyCommand.Path.ToString())
$logFile = "$logPath\$ScriptName.log"

try {
  Start-Transcript "$logFile"
}
catch {
  Write-Verbose "This host does not support transcription"
}

#-------------------------------------------------------------

# Get the script path and name
$ScriptPath = {Split-Path $MyInvocation.ScriptName}
$ScriptPath = $(&$ScriptPath)
$ScriptName = [System.IO.Path]::GetFilenameWithoutExtension($MyInvocation.MyCommand.Path.ToString())

# Set the name and path for the XMLFile
$XMLFilePath = "$ScriptPath\$ScriptName*.xml"

$MaxThreads = ((Get-WmiObject Win32_Processor) | Measure-Object -Sum -Property NumberOfLogicalProcessors).Sum -1
$RunspaceCollection = @()
$RunspacePool = [runspacefactory]::CreateRunspacePool(
    1, # minimum number of opened/concurrent runspaces for the pool
    $MaxThreads # maximum number of opened/concurrent runspaces for the pool
  )
$RunspacePool.open()

#-------------------------------------------------------------

$scriptBlockRead = {
  param([string]$File)
  $Output = "Reading `"$File`"..."
  If ([System.IO.File]::Exists($File)) {
    $sw = [Diagnostics.Stopwatch]::StartNew()
    [Byte[]]$Bytes = [System.IO.File]::ReadAllBytes($File)
    $sw.Stop()
    If ([Int]($Bytes.Count) -ge 0) {
      $Output += "`r`n- Read in sucessfully"
      $Output += "`r`n- Completed in $($sw.Elapsed.TotalMilliseconds) ms"
    } Else {
      $Output += "`r`n- Failed to read"
    }
  } Else {
    $Output += "`r`n- File does not exist"
  }
  $Output
}

# Have left this script block in the script so you can run a comparison between
# the two different methods for binary reads. [System.IO.File]::ReadAllBytes is
# much faster.
$scriptBlockRead2 = {
  param([string]$File)
  $Output = "Reading `"$File`"..."
  If (Test-Path -path "$File") {
    $sw = [Diagnostics.Stopwatch]::StartNew()
    [Byte[]]$Bytes = Get-Content -Path "$File" -Encoding Byte -ReadCount 0
    $sw.Stop()
    If ([Int]($Bytes.Count) -ge 0) {
      $Output += "`r`n- Read in sucessfully"
      $Output += "`r`n- Completed in $($sw.Elapsed.TotalMilliseconds) ms"
    } Else {
      $Output += "`r`n- Failed to read"
    }
  } Else {
    $Output += "`r`n- File does not exist"
  }
  $Output
}

#-------------------------------------------------------------

$scriptBlockExecute = {
  param(
        [string]$ApplicationName,
        [string]$ProcessPath,
        [string]$ProcessExecutable,
        [string]$CommandLineContains,
        [string]$ExtraProcessesToTerminate,
        [string]$TerminateAfterInSeconds
       )

  Function StartProcess {
    param (
           [string]$ProcessPath,
           [string]$ProcessName
          )
    if (!([String]::IsNullOrEmpty($ProcessPath))) {
      if (Test-Path -path "$ProcessPath") {
        if (Test-Path -path "$ProcessPath\$ProcessName") {
          $ProcessName = "$ProcessPath\$ProcessName"
        } Else {
          write-warning "The `"$ProcessPath\$ProcessName`" file does not exist" -verbose
          write-verbose "Will attempt to start the `"$ProcessName`" without specifying a path." -verbose
        }
      } Else {
        write-warning "The `"$ProcessPath`" path does not exist" -verbose
        write-verbose "Will attempt to start the `"$ProcessName`" without specifying a path." -verbose
      }
    }
    write-verbose "Starting the `"$ProcessName`" process..." -verbose
    #(Start-Process $ProcessName" -Passthru).ExitCode
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = "$ProcessName"
    $pinfo.UseShellExecute = $false
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    Try {
      $result = $p.Start()
    }
    Catch {
      $result = $False
    }
    If ($result) {
      write-verbose "Process started successfully." -verbose
    } Else {
      write-warning "Process failed to start." -verbose
    }
    $p.Dispose()
    return $result
  }

  Function TerminateProcess {
    param (
           [string]$ProcessName,
           [string]$CommandLineContains
          )
    $delaystart = 0
    $interval = 1
    $repeat = 5
    $exitwhenfound = $True
    Start-Sleep -Seconds $delaystart
    if ([String]::IsNullOrEmpty($CommandLineContains)) {
      Write-Verbose "Killing the $ProcessName process..." -verbose
    } Else {
      Write-Verbose "Killing the $ProcessName process which contains `"$CommandLineContains`" in it's command line..." -verbose
    }
    Do {
      $i = 0
      Do {
        $ProcessFound = $False
        Try {
          $Processes = Get-WMIObject Win32_Process -Filter "name='$ProcessName'" -ErrorAction Stop | Where-Object {$_.commandline -Like "*$CommandLineContains*"}
        }
        Catch {
          write-verbose $_.Exception.InnerException.Message -verbose
        }
        If (($Processes | Measure-Object).Count -gt 0) {
          $ProcessFound = $True
        }
        $i++
        If ($i -eq $repeat) {
          break 
        }
        Start-Sleep -Seconds $interval
      } Until ($ProcessFound -eq $true)
      If ($ProcessFound) {
        write-verbose "Process '$ProcessName' was found." -verbose
        if (!([String]::IsNullOrEmpty($CommandLineContains))) {
          write-verbose "Process command line contains: '$CommandLineContains'" -verbose
        }
        ForEach ($Process in $Processes) {
          Try {
            $Return = ([wmi]$Process.__RELPATH).terminate()
            If ($Return.ReturnValue -eq 0) {
              write-verbose "Process terminated without error." -verbose
            } Else {
              write-verbose "Process failed to terminate: $($Return.ReturnValue)" -verbose
            }
          }
          Catch {
            write-verbose $_.Exception.Message -verbose
          }
        }
      } Else {
        If ($exitwhenfound) {
          write-verbose "Process '$ProcessName' was not found. Giving up!" -verbose
        } Else {
          write-verbose "Process '$ProcessName' was not found. Trying again!" -verbose
        }
      }
    } Until ($exitwhenfound -eq $true)
  }

  # Function to parse a string to integer. It uses the TryParse method on [Int32]
  # to attempt to parse a string into a number and then writes the results
  # - http://pshscripts.blogspot.com.au/2011/06/
  Function TryToParse { 
    # Parameter to parse into a number 
    Param ([string] $value)
    # Define $number and try the parse 
    [int] $number = 0 #used after as refence
    # Try to cast string as integer and put parsed value in reference variable
    $result = [System.Int32]::TryParse($value, [ref] $number); 
    if ($result)  { 
      return $number  
    } else {
      if ($value -eq $null) {
        $value = ""
      }
      return 1
    }
  }

  $Output = "Starting `"$ApplicationName`""
  If (Test-Path -path "$ProcessPath\$ProcessExecutable") {
    $IsStarted = StartProcess -ProcessPath:"$ProcessPath" -ProcessName:"$ProcessExecutable"
    If ($IsStarted) {
      $TerminateAfter = TryToParse($TerminateAfterInSeconds)
      $Output += "`r`n- Waiting for $TerminateAfter seconds"
      Start-Sleep -Seconds $TerminateAfter
      $Output += "`r`n- Terminating `"$ApplicationName`""
      TerminateProcess -ProcessName:"$ProcessExecutable" -CommandLineContains:"$CommandLineContains"
      If ($ExtraProcessesToTerminate -ne "") {
        ($ExtraProcessesToTerminate).Split(',') | ForEach {
          $Output += "`r`n- Terminating `"$($_)`""
          TerminateProcess -ProcessName:"$_" -CommandLineContains:""
        }
      }
    }
  } Else {
    $Output += "`r`n- File does not exist"
  }
  $Output
}

#-------------------------------------------------------------

# Get the XML files
$XMLFiles = Get-ChildItem "$XMLFilePath" |  Select-Object -ExpandProperty FullName
$CountXMLFiles = ($XMLFiles | Measure-Object).Count
Write-Verbose "$(Get-Date): There are $CountXMLFiles XML files to process" -verbose

$ContainsElements = $False

ForEach ($XMLFile in $XMLFiles) {
  Write-Verbose "$(Get-Date): ---------PROCESSING THE INPUT FILE-----------" -verbose
  Write-Verbose "$(Get-Date): Processing $($XMLFile)" -verbose

  If (Test-Path -path $XMLFile) {

    # Create the XML Object and open the XML file
    $XmlDocument = Get-Content -path $XMLFile
    # Uncomment the following lines for debugging purposes only
    #$XmlDocument.configuration.Processes
    #$XmlDocument.configuration.Processes.Process | Format-Table -Autosize
    #$XmlDocument.configuration.Folders
    #$XmlDocument.configuration.Folders.Folder | Format-Table -Autosize

    $ContainsElements = $False
    $Folders = $False
    $Processes = $False
    Try {
      $XmlDocument.configuration.Folders.Folder | out-null
      $ContainsElements = $True
      $Folders = $True
    }
    Catch {
      # Does not contain valid elements
    }
    Try {
      $XmlDocument.configuration.Processes.Process | out-null
      $ContainsElements = $True
      $Processes = $True
    }
    Catch {
      # Does not contain valid elements
    }

    If ($ContainsElements -AND $Processes) {
      foreach ($Process in $XmlDocument.configuration.Processes.Process) {

        # Uncomment the following lines for debugging purposes only
        #$Process
        #$Process.Name
        #$Process.Path
        #$Process.Executable
        #$Process.Read
        #$Process.CommandLineContains
        #$Process.ExtraProcessesToTerminate
        #$Process.TerminateAfterInSeconds

        $ApplicationName = "$($Process.Name)"
        $ProcessPath = $($Process.Path)
        $ProcessPath = $ProcessPath.Replace("%ProgramFiles(x86)%",${env:ProgramFiles(x86)})
        $ProcessPath = $ProcessPath.Replace("%ProgramFiles%",${env:ProgramFiles})
        $ProcessPath = $ProcessPath.Replace("%ProgramData%",${env:ProgramData})
        $ProcessPath = $ProcessPath.Replace("%SystemDrive%",${env:SystemDrive})
        $ProcessPath = $ProcessPath.Replace("%SystemRoot%",${env:SystemRoot})
        $ProcessExecutable = "$($Process.Executable)"
        $CommandLineContains = "$($Process.CommandLineContains)"
        $ExtraProcessesToTerminate = "$($Process.ExtraProcessesToTerminate)"
        $TerminateAfterInSeconds = "$($Process.TerminateAfterInSeconds)"
        try {
          $Read = [System.Convert]::ToBoolean($Process.Read) 
        } catch [FormatException] {
          $Read = $false
        }

        If ($Read) {
          $PSinstance = [PowerShell]::Create().AddScript($ScriptBlockRead).AddArgument("$ProcessPath\$ProcessExecutable")
        } Else {
          $PSinstance = [PowerShell]::Create()
          $null = $PSinstance.AddScript($ScriptBlockExecute)
          $null = $PSinstance.AddArgument($ApplicationName)
          $null = $PSinstance.AddArgument($ProcessPath)
          $null = $PSinstance.AddArgument($ProcessExecutable)
          $null = $PSinstance.AddArgument($CommandLineContains)
          $null = $PSinstance.AddArgument($ExtraProcessesToTerminate)
          $null = $PSinstance.AddArgument($TerminateAfterInSeconds)
        }

        $PSinstance.RunspacePool = $RunspacePool
        $obj = New-Object -TypeName PSObject
        $obj | Add-Member -MemberType NoteProperty -Name "JobName" -value "$ApplicationName"
        $obj | Add-Member -MemberType NoteProperty -Name "Runspace" -value $PSinstance.BeginInvoke()
        $obj | Add-Member -MemberType NoteProperty -Name "PowerShell" -value $PSinstance
        [Collections.Arraylist]$RunspaceCollection += $obj

        write-verbose "$(Get-Date): Runspace created: $ApplicationName" -verbose

        $obj = $Null
      }
    }
    If ($ContainsElements -AND $Folders) {
      foreach ($Folder in $XmlDocument.configuration.Folders.Folder) {

        # Uncomment the following lines for debugging purposes only
        #$Folder
        #$Folder.Path
        #$Folder.Extensions
        #$Folder.Recurse

        $FolderPath = $($Folder.Path)
        $FolderPath = $FolderPath.Replace("%ProgramFiles(x86)%",${env:ProgramFiles(x86)})
        $FolderPath = $FolderPath.Replace("%ProgramFiles%",${env:ProgramFiles})
        $FolderPath = $FolderPath.Replace("%ProgramData%",${env:ProgramData})
        $FolderPath = $FolderPath.Replace("%SystemDrive%",${env:SystemDrive})
        $FolderPath = $FolderPath.Replace("%SystemRoot%",${env:SystemRoot})
        [array]$FolderExtensions = ($Folder.Extensions).Split(",")
        try {
          $Recurse = [System.Convert]::ToBoolean($Folder.Recurse) 
        } catch [FormatException] {
          $Recurse = $false
        }
        If (Test-Path -Path "$FolderPath") {
          Get-ChildItem "$FolderPath" -Include $FolderExtensions -Recurse:$True | ForEach-Object {
            $FullName = $_.FullName

            $PSinstance = [PowerShell]::Create().AddScript($ScriptBlockRead).AddArgument("$FullName")

            $PSinstance.RunspacePool = $RunspacePool
            $obj = New-Object -TypeName PSObject
            $obj | Add-Member -MemberType NoteProperty -Name "JobName" -value "$FullName"
            $obj | Add-Member -MemberType NoteProperty -Name "Runspace" -value $PSinstance.BeginInvoke()
            $obj | Add-Member -MemberType NoteProperty -Name "PowerShell" -value $PSinstance
            [Collections.Arraylist]$RunspaceCollection += $obj

            write-verbose "$(Get-Date): Runspace created: $FullName" -verbose

            $obj = $Null

          }
        } Else {
          write-verbose "$(Get-Date): The `"$FolderPath`" path does not exist" -verbose
        }
      }
    }
    If ($ContainsElements -eq $False) {
      write-verbose "$(Get-Date): The XML File does not contain valid elements" -verbose
    }
  }
}

If ($ContainsElements) {
  [Collections.Arraylist]$Results = @()
  # Use a sleep timer to control CPU utilization
  $SleepTimer = 200
  Write-Verbose "$(Get-Date): --------WAITING FOR JOBS TO COMPLETE---------" -verbose

  While($RunspaceCollection) {
    Foreach ($Runspace in $RunspaceCollection.ToArray()) {
      # Here's where we actually check if the Runspace has completed
      If ($Runspace.Runspace.IsCompleted) {
        # Get the results from the runspace before cleaning it up
        [void]$Results.Add($Runspace.PowerShell.EndInvoke($Runspace.Runspace))
        write-verbose "$(Get-Date): Runspace complete: $($runspace.JobName)" -verbose
        $Runspace.PowerShell.Dispose()
        $RunspaceCollection.Remove($Runspace)
      }
    }
    Start-Sleep -Milliseconds $SleepTimer
  }

  Write-Verbose "$(Get-Date): -------------OUTPUT THE RESULTS--------------" -verbose
  # Output the results
  ForEach ($Output in $Results) {
    ForEach ($line in $($Output -split "`r`n")) {
      write-verbose "$(Get-Date): $line" -verbose
    }
  }
  Write-Verbose "$(Get-Date): ---------------------------------------------" -verbose
}

#-------------------------------------------------------------

$EndDTM = (Get-Date)
Write-Verbose "Elapsed Time: $(($EndDTM-$StartDTM).TotalSeconds) Seconds" -Verbose
Write-Verbose "Elapsed Time: $(($EndDTM-$StartDTM).TotalMinutes) Minutes" -Verbose

# Stop the transcript
try {
  Stop-Transcript
}
catch {
  Write-Verbose "$(Get-Date): This host does not support transcription"
}

Enjoy!

Jeremy Saunders

Jeremy Saunders

Technical Architect | DevOps Evangelist | Software Developer | Microsoft, NVIDIA, Citrix and Desktop Virtualisation (VDI) Specialist/Expert | Rapper | Improvisor | Comedian | Property Investor | Kayaking enthusiast at J House Consulting
Jeremy Saunders is the Problem Terminator. He is a highly respected IT Professional with over 35 years’ experience in the industry. Using his exceptional design and problem solving skills with precise methodologies applied at both technical and business levels he is always focused on achieving the best business outcomes. He worked as an independent consultant until September 2017, when he took up a full time role at BHP, one of the largest and most innovative global mining companies. With a diverse skill set, high ethical standards, and attention to detail, coupled with a friendly nature and great sense of humour, Jeremy aligns to industry and vendor best practices, which puts him amongst the leaders of his field. He is intensely passionate about solving technology problems for his organisation, their customers and the tech community, to improve the user experience, reliability and operational support. Views and IP shared on this site belong to Jeremy.
Jeremy Saunders
Jeremy Saunders

Previous post:

Next post: