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.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<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.

1
2
3
4
5
6
7
$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
1
2
3
4
5
6
7
$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 (314 downloads)  in the in the form of a zip file, which includes the PowerShell script and XML file.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<#
  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.

Previous post:

Next post: