PowerShell: search for a file path in the top level of a folder; warn the user if it's not found and proceed to search recursively

Solution 1:

The issue is an awkward behavior from Copy-Item. If you pass an empty/null collection through the pipeline (like from Get-ChildItem), it doesn't error out. Different than you may expect, since piping in $null does throw an error:

Get-ChildItem './MySrc' -Filter 'BadFilter' | Copy-Item ./MyDst  ## No Error
$Null | Copy-Item ./MyDst  ## Does Error

For files, I prefer a structure like If (Test-Path){} over Try/Catch in order to make sure paths and such are still valid before attempting changes:

# Check if file exists in correct path and copy,
If (Test-Path "$CurrentDir\$_") {
  Copy-Item -Force -Path "$CurrentDir\$_" -Destination .\marking
}

# Otherwise check recursively for the correct file and show a warning if found
ElseIf (Get-ChildItem -Path $CurrentDir -File -Recurse -Filter "$_") {
  Write-Warning "$StudentNumber did not follow the specified folder convention, but all files were submitted."
  Get-ChildItem -Path $CurrentDir -File -Recurse -Filter "$_" |
    Copy-Item -Force -Destination .\marking
}

# Error out if file not found
Else { 
  Write-Error -Message "$StudentNumber did not submit any of: $DoneFiles." -Category InvalidData
  Read-Host -Prompt "Press Enter to continue"
}