PowerShell 7.3 - Handling 'FileNotFoundException' When Attempting to Copy Files with Dynamic Source Paths
I've hit a wall trying to Quick question that's been bugging me - I'm running into a `FileNotFoundException` when trying to copy files from dynamically generated paths in a PowerShell script... The script is supposed to read a list of file paths from a CSV, then copy each file to a target directory. However, I keep getting this error for some of the files. Here's a simplified version of what I've done: ```powershell # Sample CSV import $fileList = Import-Csv -Path 'C:\path\to\filelist.csv' # Target directory $targetDir = 'C:\path\to\target' foreach ($file in $fileList) { $sourcePath = $file.SourcePath try { Copy-Item -Path $sourcePath -Destination $targetDir -ErrorAction Stop Write-Host "Copied $sourcePath to $targetDir" } catch [System.IO.FileNotFoundException] { Write-Host "Error: File not found at $sourcePath" } catch { Write-Host "An unexpected error occurred: $_" } } ``` The CSV file looks something like this: ``` SourcePath C:\files\file1.txt C:\files\file2.txt C:\files\file3.txt ``` Despite the paths appearing correct, I'm getting the `FileNotFoundException` intermittently. For example, it fails on `C:\files\file2.txt` but not on `file1.txt`. I've verified that the paths are correct and that the files exist before running the script. The script also has permission to access these files. I've tried adding logging to see what paths are being processed, but they all look correct. I'm not sure if there's a timing issue, a file lock, or something else at play here. Any advice on how to troubleshoot this or avoid the `FileNotFoundException` would be greatly appreciated! For context: I'm using Powershell on macOS. Am I missing something obvious? This is my first time working with Powershell latest.