【发布时间】: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