Home > Net >  Create error-logfile only if there is an error
Create error-logfile only if there is an error

Time:03-11

I have a simple powershell-script which I use to execute a python-script. I have predefined paths for redirectStandardOutput and redirectstandarderror so I can check on the execution afterwards.

$datestring = (Get-Date).ToString(“s”).Replace(“:”,”-”) 
$base_path = "C:\mypath"
$python = $base_path   "\...\python.exe"
$py_file = $base_path   "\ScriptsPython\myscript.py"
$log_path = $base_path   "\Logfiles\myscript_$datestring.txt"
$log_path_error = $base_path   "\Logfiles\error_myscript_$datestring.txt"

cd "$base_path\...\" 
start-process -FilePath $python """$py_file""" -redirectStandardOutput $log_path -RedirectStandardError $log_path_error -NoNewWindow

The script works perfectly fine. The only thing that bothers me is that even if there isn't an error it still creates an error-logfile which is empty. Is there a way to tell powershell only create an error-logfile if there actually is an error?

CodePudding user response:

You should read on try/catch/finaly

CodePudding user response:

Use the "Try/Catch" instruction, so if there is an error in the "Try" instruction, the script will continue using the "Catch" block.

For example:

Try
{
    Your script here...
}
Catch
{
    If there is an error in the "Try" block, the script goes into "Catch" block.
    Create an Error Message / Log file.
}

You can also add exceptions so if there is a specific error, it goes in a different catch block and returns a different code.

  • Related