Home > Software design >  Need to create a summary of errors at the end of a powershell script
Need to create a summary of errors at the end of a powershell script

Time:03-31

I have an idea in my head and I will do my best to try and explain what I am trying to do. I have a script that basically takes a bunch of files and copies them to a new location and renames them, pretty simple. As the number of files grow it is becoming tedious to scroll through and check each line to make sure the file copied successfully. Here is a sample of the code I am using for each file:

    if ( $(Try { Test-Path $source.trim() } Catch { $false }) ) {
    Write-Host "Source file was found, now copying."
    mv -v -f $source $filedest
    Write-Host "Source has been copied, moving onto the next section.!!!!!"
  }
 Else {
    Write-Host "Source file was NOT found, moving onto the next section.XXXXX"
  }

I call out all the variables at the beginning of the script and just copy this format using unique variable names. So what this does is let me look for '!!!!!' or 'XXXXX' to see if the file was copied.

What I would like to do is have the entire file run and then have some kind of summary at the bottom that says something like:

Success: 15

Failures: 2

Failure File Name(s):

file7.csv

file12.csv

CodePudding user response:

Use 2 variables to keep track of the success count and list of files not found:

$successCount = 0
$failedFileNames = @()

# ...

if ( $(Try { Test-Path $source.trim() } Catch { $false }) ) {
    Write-Host "Source file was found, now copying."
    mv -v -f $source $filedest
    Write-Host "Source has been copied, moving onto the next section.!!!!!"

    # update success counter
    $successCount  
}
else {
    Write-Host "Source file was NOT found, moving onto the next section.XXXXX"
    
    # no file found, add source value to list of failed file names
    $failedFileNames  = $source
}

Then when you're ready to compile your report, simply use the Count of the array of failed file names:

Write-Host "Success: $successCount"
Write-Host "Failure: $($failedFileNames.Count)"
Write-Host "Failed file(s):"
$failedFileNames |Write-Host
  • Related