How to remove Space from the beginning of a File Name in PowerShell

Viewed 83

I have used these codes but none of them worked:

get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace('^ ', "") }

get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace('^[[:space:]]', "") }

get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace('^[" "]', "") }

get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace('^\s', "") }
1 Answers

As commenter Santiago Squarzon correctly wrote, the String.Replace() method does not support RegEx.

The clearest way to remove any sequence of whitespace from the start is String.TrimStart():

Get-ChildItem *.mp3 | Rename-Item -NewName { $_.Name.TrimStart() }

If you actually want to remove only a single whitespace character from the start, you could use RegEx through the -replace operator:

Get-ChildItem *.mp3 | Rename-Item -NewName { $_.Name -replace '^\s' }

Unrelated improvement:

I have removed ForEach-Object (alias foreach). The -Path parameter can be fed directly from the pipeline. The argument for -NewName can be a delay-bind script block, because the parameter also accepts pipeline input.

Related