Bird
0
0

Given the list @('file1.txt','file2.doc','file3.txt'), which PowerShell ForEach loop correctly outputs only the filenames ending with '.txt'?

hard📝 Application Q8 of 15
PowerShell - Control Flow
Given the list @('file1.txt','file2.doc','file3.txt'), which PowerShell ForEach loop correctly outputs only the filenames ending with '.txt'?
Aforeach ($f in $files) { if ($f -contains '.txt') { Write-Output $f } }
Bforeach ($f in $files) { Write-Output $f -match '.txt' }
Cforeach ($f in $files) { if ($f -like '*.txt') { Write-Output $f } }
Dforeach ($f in $files) { Write-Output $f | Where-Object { $_ -eq '.txt' } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand filtering

    Use -like '*.txt' to match filenames ending with '.txt'.
  2. Step 2: Check each option

    foreach ($f in $files) { if ($f -like '*.txt') { Write-Output $f } } correctly uses if ($f -like '*.txt') to filter.
  3. Final Answer:

    foreach ($f in $files) { if ($f -like '*.txt') { Write-Output $f } } -> Option C
  4. Quick Check:

    Use -like with wildcard for string matching [OK]
Quick Trick: Use '-like "*.txt"' to filter filenames [OK]
Common Mistakes:
  • Using -contains instead of -like for string matching
  • Misusing Write-Output with -match operator
  • Piping Write-Output incorrectly inside loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes