1

I have a PowerShell script that performs numerous file management tasks and occasionally I have the need to terminate the script before it has finished processing. In order to terminate the script cleanly and not leave any files dotted around, I have the script read in a variable from a config file every time the foreach of the gci results is processed, as below:

Get-ChildItem $fileDir -Filter *.doc | Foreach-Object {
    Get-Content $confFile | Foreach-Object {
        $var = $_.Split('=')
        New-Variable -Name $var[0] -Value $var[1] -Force
    }
    if ($process -eq "TRUE") {
        <process File operations>
    }
}

This allows me to change the value of process in the config file to anything but TRUE and the script will skip the process (although still loop though until complete).

Is there anyway to use a keyboard shortcut to exit the script in a controlled fashion? i.e. after an iteration of the foreach loop has completed. e.g. Press Ctrl+Q and it will exit cleanly as opposed to Ctrl+C.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Rob Berry
  • 185
  • 1
  • 4
  • 14
  • 3
    Possible duplicate of [Gracefully stopping in Powershell](https://stackoverflow.com/questions/1710698/gracefully-stopping-in-powershell) – Clijsters Nov 30 '17 at 09:29
  • 3
    _occasionally I have the need to terminate the script before it has finished_ this is in fact a design problem. – Clijsters Nov 30 '17 at 09:29

0 Answers0