I have a PowerShell script that gets a list of file names from a file, searches a folder for the file names, archives them, and then does other stuff.
#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
}
The try-catch isn't working as expected. I have a file name in the file list that is not present in $some_path. I was expecting try-catch to stop the execution and do the Write-Host. Instead, it doesn't run the Write-Host and continues to the $data = Get-Content $current_file
step, which is throwing a terminating error because the path doesn't exist for the missing file. How can I fix this?