Batch Replace spaces in filenames

Using the Get-ChildItem Cmdlet to to batch replace whitespace in file names.
created by on 2013-07-04

If you want to quickly replace all spaces (or other charachters) in a number of files you use the Get-ChildItem Cmdlet in conjunction with ForEach-Object:

Screenshot: A folder with a number of files which contain spaces

Test the script

If you want to test the script without acctually changing anything you can use the -WhatIf switch:

Get-ChildItem -Recurse | Where-Object { $_.Name -match '\s' -and (-not($_.psIsContainer))} | ForEach-Object { ren $_.fullName ($_.Name -replace '\s', '-') -WhatIf}

The -WhatIf switch will instruct the script to only print out what it would do:

Screenshot: Executing the white space replace script with the WhatIf Switch turned on

Execute the script

To execute the script just move to the directory which contains the file files you want to rename and paste the following command in your PowerShell console:

Get-ChildItem -Recurse | Where-Object { $_.Name -match '\s' -and (-not($_.psIsContainer))} | ForEach-Object { ren $_.fullName ($_.Name -replace '\s', '-')}

Screenshot: The result of the script execution

Related Links

Fork allmark on GitHub