Bird
0
0

You want to filter a list of filenames to include only those that start with 'log' and end with a 4-digit year using PowerShell. Which command correctly uses -match to do this?

hard📝 Application Q15 of 15
PowerShell - Operators
You want to filter a list of filenames to include only those that start with 'log' and end with a 4-digit year using PowerShell. Which command correctly uses -match to do this?
$files = @('log2020.txt', 'log2019.csv', 'data2020.log', 'log20a0.txt')
A$files | Where-Object { $_ -like 'log????' }
B$files | Where-Object { $_ -like 'log*2020' }
C$files | Where-Object { $_ -match 'log\d{4}$' }
D$files | Where-Object { $_ -match '^log\d{4}' }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the pattern requirements

    We want filenames starting with 'log' (^log) followed immediately by exactly 4 digits (\d{4}).
  2. Step 2: Analyze each option

    $files | Where-Object { $_ -match '^log\d{4}' } uses regex '^log\d{4}' which matches strings starting with 'log' plus 4 digits. $files | Where-Object { $_ -like 'log????' } uses -like with 'log????' which matches 'log' plus any 4 characters but not necessarily digits. $files | Where-Object { $_ -match 'log\d{4}$' } matches 'log' followed by 4 digits at the end, but the year is not necessarily at the end of the filename. $files | Where-Object { $_ -like 'log*2020' } matches 'log' followed by anything and ending with '2020', which is too specific.
  3. Final Answer:

    $files | Where-Object { $_ -match '^log\d{4}' } -> Option D
  4. Quick Check:

    Start with 'log' + 4 digits = $files | Where-Object { $_ -match '^log\d{4}' } [OK]
Quick Trick: Use ^ for start and \d{4} for 4 digits in regex [OK]
Common Mistakes:
  • Using -like with ? instead of digits
  • Matching digits at end instead of start
  • Confusing -like and -match patterns

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes