Batch script to remove # from a file name (only in a specific directory)

I'm looking for a script to remove the # character out of any file names in a specific directory (PDF documents).

I've been looking at some similar examples, but it's all a bit confusing!


@echo off &setlocal
cd /d c:\users\data
for /f "delims=" %%a in ('dir /b /a-d *#*.pdf') do (
    set "fname=%%~a"
    setlocal enabledelayedexpansion
    set "nname=!fname:#=!"
    ren "!fname!" "!nname!"
    endlocal
)

It's 2013, you should use PowerShell:

Get-ChildItem | Where-Object {$_.Name -match '#'} | ForEach-Object { Rename-Item -Path $_.Name -NewName $($_.Name -Replace "#", "") -WhatIf }

Navigate to the directory in question and execute the line. It finds all files with a # and then renames each of them. Remove the '-Whatif' to actually perform the operation.

A shorter version using aliases and defaults would be:

ls | ? {$_.Name -match "#"} | ForEach { rni $_.Name $($_.Name -Replace "#", "")}

As least the long version seems more readable to me than the 1980s batch syntax. The only cryptic part here is the '$.Name', '$' in PowerShell refers to the current object in the loop. Here in all cases to the current file. Because we need an expression for the -NewName parameter, we have to wrap it into $()