1

我有以下代码:

$items = Get-ChildItem -Path 'D:\Myoutput\'
$items | ForEach-Object 
{
  $lastWrite = ($_).LastWriteTime
  $timespan = New-Timespan -days 3 -hours 0 -Minutes 0
  if(((get-date) - $lastWrite) -gt $timespan) {
    $name = $_.Name
    $isDir = $_.PSIsContainer
    if(!$isDir) {
      $_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive\$name.zip"
      if (**above_line** is success) {
       echo "$name is zipped"
       $_ | Remove-Item
      }
    }
  }
}

请帮忙,我怎样才能知道'$_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive$name.zip"' 是否成功。

4

2 回答 2

0

Compress-Archive如果失败已经抛出错误,您可以在删除原始文件之前捕获它。例如,我continue用来跳过其余的命令。您还可以使用以下命令跳过检查文件夹Get-ChildItem -File

Foreach ($file in (Get-Item C:\temp\ -File)) {
  Try { $file | Compress-Archive -DestinationPath C:\BadPath\test.zip }
  Catch { Write-Warning ("Skipping file due to error: " + $file.FullName); continue }
  Remove-Item $file
}

当我使用上面的 Bad path 时,输出如下所示:

WARNING: Skipping file due to error: C:\temp\test1.txt
WARNING: Skipping file due to error: C:\temp\test2.txt

并且这些文件不会被删除。

于 2021-09-09T17:15:25.103 回答
0

Compress-Archive如果出现问题,将抛出异常,并将删除部分创建的档案(source)。所以,你可以做两件事来确保它是成功的:

  1. 捕获异常
  2. 测试存档是否存在

例子:

$items = Get-ChildItem -Path 'D:\Myoutput\'
$items | ForEach-Object 
{
  $lastWrite = ($_).LastWriteTime
  $timespan = New-Timespan -days 3 -hours 0 -Minutes 0
  if(((get-date) - $lastWrite) -gt $timespan) {
    $name = $_.Name
    $isDir = $_.PSIsContainer
    if(!$isDir) {
      try {
        $_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive\$name.zip"
        if (Test-Path -Path "D:\Myoutput\Archive\$name.zip") {
          Write-Host "$name is zipped"
          $_ | Remove-Item
        } else {
          Write-Host "$name is NOT zipped" -ForegroundColor Red
        }
      } catch {
        Write-Host "$name is NOT zipped" -ForegroundColor Red
      }
    }
  }
}
于 2021-09-09T17:26:27.460 回答