0

I have a powershell script which starts 2 different Access database applications running. This in a volunteer setting and when the computer is first turned on, it can take a minute or two for the startup to complete. Sometimes the user gets impatient and clicks on the shortcut to the Powershell script more than once, causing the Access databases to start multiple times.

To solve this I thought that the first thing that the script would do would be to create a file. If the create failed due to the file already existing, it would ask the user if they wanted to continue. If yes, run the rest of the script otherwise exit. The problem is that the "catch" after the "try" isn't catching anything. How do I fix this and/or what other solutions do people have?

try {New-Item ($dbDir + "lock_file") -type file | Out-Null} # create lock_file. If it exists, another copy of this is probably running and the catch will run catch { $answer = [System.Windows.Forms.MessageBox]::Show("It appears that the database is already starting. Start again?" , "Start Again" , 4) if ($answer -eq "NO") {Exit} } 
2
  • 2
    I dont think you are getting a terminating error which is what catch needs. You could add the parameter -ErrorAction Stop to New-Item Commented Oct 28, 2014 at 19:46
  • Put it as answer, Is does the trick. Commented Oct 28, 2014 at 20:21

1 Answer 1

1

Catch only works for terminating errors. Cmdlets that throw errors but continue processing will not be caught by catch (Also called non-terminating errors). One way to change this behavior is to set the -erroraction of a cmdlet which should be common to most of them. In your case I would do this:

try {New-Item ($dbDir + "lock_file") -type file -ErrorAction Stop | Out-Null} 

The catch block should trigger now.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info. I added the "-ErrorAction Stop" and it works just fine now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.