Powershell Runs Out of Catch When Error Occurs in try-catch Catch

Asked 2 years ago, Updated 2 years ago, 80 views

Please forgive me if this is my first question and I am not used to it.
There is an event like the one mentioned in the title.
If you create and run a program like the one below, the first one will be successful.
Then, if you read-only (or run the program on another user) C:\hoge1\hoge, the Stop-TranScript error will result in a catch or subsequent statement.
If an error occurs in the catch, it appears that the subsequent statement is interrupted and the statement outside the catch is executed.
If there is a way to avoid it, I would appreciate it if you could advise me (check Win10_20H2)

Start-TranScript-Path C:\hoge1\hoge
try{
    echo hoge>C:\hoge2\hogehoge# No folder exists
}
catch{
    echo$_.Exception.Message
    Stop - TranScript
    exit5
}
echo "For some reason, this is where it runs"

powershell

2022-09-29 21:56

1 Answers

Like other shell scripts, PowerShell continues to process errors.This behavior can be controlled by the Common Parameter -ErrorAction.
The default is -ErrorAction Continue, but -ErrorAction Stop stops.

However, the question is redirected by > and

echo hoge>C:\hoge2\hogehoge

is internally

Write-Output hoge | Out-File C:\hoge2\hogehoge

appears.

Write-Output hoge | Out-File-ErrorAction Stop C:\hoge2\hogehoge

This stops, but the original redirect notation does not allow you to specify parameters.You can still control this with $ErrorActionPreference in the Preference Variable.Before Run

can stop the processing.


2022-09-29 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.