简体   繁体   English

需要在 powershell 脚本末尾创建错误摘要

[英]Need to create a summary of errors at the end of a powershell script

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.或“XXXXX”以查看文件是否已复制。

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成功:15

Failures: 2失败:2

Failure File Name(s):失败文件名:

file7.csv文件7.csv

file12.csv文件12.csv

Use 2 variables to keep track of the success count and list of files not found:使用 2 个变量来跟踪成功计数和未找到的文件列表:

$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:然后,当您准备好编译报告时,只需使用失败文件名数组的Count

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM