How to Search for MP3 Files Under 5MB Using PowerShell?

0
10
Asked By CuriousCat42 On

I'm trying to use PowerShell to find all MP3 files that are under 5MB in size from a specific directory. Here's the command I'm trying, but I'm running into a parsing error:

```powershell
$( $Files = Get-ChildItem -Path "\PC\Users\name\Music" -Recurse -Filter *.mp3 | Where-Object {$_.Length -lt 5MB} | Sort-Object Length) $Files | ForEach-Object { "$($_.FullName) - $(\'{0:N2}\' -f ($_.Length/1Kb))Kb" } >>C:tmpoutput.txt
```

The error says there's an unexpected token '$Files' in my command. I admit I'm not very experienced with PowerShell, so I'm unsure why this isn't working. Any help?

3 Answers

Answered By PowerShellWizard4 On

Make sure you define `$Files` separately from the usage. You should split your command into two parts:

1. Define `$Files`:
```powershell
$Files = Get-ChildItem -Path "\PC\Users\name\Music" -Recurse -Filter *.mp3 | Where-Object {$_.Length -lt 5MB} | Sort-Object Length
```
2. Then use `$Files`:
```powershell
$Files | ForEach-Object { "$($_.FullName) - $('{0:N2}' -f ($_.Length/1Kb))Kb" } >>C:tmpoutput.txt
```

This should resolve the parsing errors you're seeing.

Answered By ScriptGuru99 On

It's worth trying to simplify your approach. You can remove both occurrences of `$Files` and pipe directly from `Get-ChildItem` to `Where-Object` and then `ForEach-Object`. Here's an example:

```powershell
Get-ChildItem -Path "\PC\Users\name\Music" -Recurse -Filter *.mp3 | Where-Object { $_.Length -lt 5MB } | Sort-Object Length | ForEach-Object { "$($_.FullName) - $('{0:N2}' -f ($_.Length/1KB))Kb" } >>C:tmpoutput.txt
```

This way, you avoid the need for additional variable assignments.

Answered By TechSavant28 On

It looks like you should just remove the `$Files = ` part from your command. That syntax error suggests you might have combined two scripts incorrectly, so clean that up and try it again!

Keeping the script simpler might help too.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.