'Create error-logfile only if there is an error

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?



Solution 1:[1]

I think that by using parameter -RedirectStandardError, the log file is always created, whether errors will be written in it or not.
How about checking if an error log file exists and has zero length afterwards. If so, delete it?

$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

# test if the errorlog exists and if there is nothing in it, delete it
$errorFile = Get-Item -Path $log_path_error -ErrorAction SilentlyContinue
if ($errorFile -and $errorFile.Length -eq 0) { Remove-Item -Path $errorFile -Force }

P.S. Instead of concatenating strings to form a path, I would prefer using the Join-Path cmdlet.

Solution 2:[2]

You should read on try/catch/finaly

Solution 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nawad-sama
Solution 3 Nodah