【问题标题】:PowerShell: try-catch not workingPowerShell:尝试捕捉不起作用
【发布时间】:2015-10-31 20:05:10
【问题描述】:

我有一个 PowerShell 脚本,它从文件中获取文件名列表,在文件夹中搜索文件名,将它们存档,然后执行其他操作。

#make non-terminating errors behave like terminating errors (at script level)
$ErrorActionPreference = "Stop"

#set the folder that has the list and the files
$some_path = "D:\some_folder\"
$archive = "D:\archive\"

#set the list file name
$file_list = $some_path + "file_list.txt"

#get the files that I'm searching for from this list file
$files_to_retrieve = Select String -Path $file_list -Pattern "something" | Select-Object Line

#get the number of files for this search string
$n = $file_list.Length - 1

#seed the while loop counter
$i = 0

#while loop to archive and modify the files
While ($i -le $n)
{
    #set the current file name
    $current_file = $path + $files_to_retrieve[$i].Line

    try
    {
        Copy-Item -Path $current_file -Destination $archive_path
    }
    catch
    {
        Write-Host ("file " + $files_to_retrieve[$i].Line + " not found")
    }

    $data = Get-Content $current_file

    #do modifications here
}

try-catch 未按预期工作。我在 $some_path 中不存在的文件列表中有一个文件名。我期待 try-catch 停止执行并执行 Write-Host。相反,它不运行 Write-Host 并继续执行$data = Get-Content $current_file 步骤,这会引发终止错误,因为丢失文件的路径不存在。我该如何解决这个问题?

【问题讨论】:

  • 我建议您将 write-host 输出放入您的 try 块中,并检查不存在的文件是否真的被尝试复制。
  • 我只是把这段代码放在当前的 While 循环之外,放到它自己的 While 循环中。 (如果文件在应该存在的时候不存在,我什至不想尝试修改它们。)在这个单独的 While 循环中,我在 try 块中放置了一个 Write-Host。写入主机显示。因此,尝试确实正在尝试。 catch 中的 Write-Host 也会显示。这告诉我尝试确实遇到了错误。如果我在 catch 的末尾放了一个 Exit(非零),脚本就会停止。如果我不这样做,它将继续执行 While 循环中的下一步。

标签: powershell


【解决方案1】:

如您所知,您的第一个问题是try/catch。简单看一下documentation for about_Try_Catch_Finally,你会发现..

使用 Try、Catch 和 finally 块来响应或处理 终止 脚本中的错误

您的Copy-Item 行没有引发终止错误。我们使用通用参数-ErrorAction 来解决这个问题

Copy-Item -Path $current_file -Destination $archive_path -ErrorAction Stop

因此,如果出现问题,则应调用 Catch 块。假设这是那里的真正问题。


我认为您还有另一个问题,这可能只是一个错字。我不止一次看到以下 sn-p。

$file_list[$i].Line

之前您已将$file_list 声明为“D:\some_folder\file_list.txt”,这是一个字符串。我想你的意思是在下面。上面的代码将为空,因为字符串没有 line 属性。但是Select-String的返回可以!

$files_to_retrieve[$i].Line

【讨论】:

  • 除上述之外:有时我还需要将 -WarningAction 变量设置为停止(导致终止错误)以在 Powershell 中捕获警告,因为某些“错误”在某些 Powershell CMDlet 中被记录为警告.
  • 不设置 $ErrorActionPreference = "Stop" 在脚本级别否定需要在每个 try-catch 中设置 -ErrorAction Stop?
  • @Matt:你对我的错字是正确的。我的意思是写 $files_to_retrieve[$i].Line。我已经更新了帖子。
  • 另外,我在 Copy-Item 之后尝试了 -ErrorAction Stop。它不工作。当我在脚本之外运行 Copy-Item 时,它会在那里引发终止错误。但是,当我运行脚本时,它会在我的 catch 中写入语句(表明确实调用了 catch),但实际上并没有在那里终止。它尝试获取内容并在那里引发终止错误。我怀疑它包含在我的 while 循环中使其跳转到下一个 cmdlet。
  • 设置 -WarningAction Stop 也没有任何效果。
猜你喜欢
  • 2018-03-25
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 2011-02-12
  • 1970-01-01
相关资源
最近更新 更多