我有一个 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
}
Run Code Online (Sandbox Code Playgroud)
try-catch 未按预期工作。我在文件列表中有一个 $some_path 中不存在的文件名。我期待 try-catch 停止执行并执行 Write-Host。相反,它不运行 Write-Host 并继续执行该$data = Get-Content $current_file步骤,这将引发终止错误,因为缺少文件的路径不存在。我怎样才能解决这个问题?
你的第一个问题是try/catch你所知道的。简单看一下about_Try_Catch_Finally的文档,你会看到..
使用 Try、Catch 和 finally 块来响应或处理脚本中的终止错误。
您的Copy-Item线路没有引发终止错误。我们用通用参数修复它-ErrorAction
Copy-Item -Path $current_file -Destination $archive_path -ErrorAction Stop
Run Code Online (Sandbox Code Playgroud)
因此,如果出现问题,Catch则应调用该块。假设那是那里的真正问题。
我认为您还有另一个问题,这可能只是一个错字。我不止一次看到以下片段。
$file_list[$i].Line
Run Code Online (Sandbox Code Playgroud)
之前您已声明 $file_list为“D:\some_folder\file_list.txt”,它是一个字符串。我认为你的意思是在下面。上面的代码将为空,因为 string 没有 line 属性。但是从Select-String可以返回!
$files_to_retrieve[$i].Line
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4973 次 |
| 最近记录: |