Extracting File Name from Named Variable in Batch File

I needed this in order to use REN, which takes a pathless file name as its second argument.

Pretty easy with numeric variables or for loop variables. Here’s for loop variables:

set fileNameWithPath=C:\mypath\myfile.myextension
for %%X in ("%fileNameWithPath%") do set fileName=%%~nX
echo %fileName%

Here’s how to make a named variable into a numeric variable, by passing it to a subroutine.

set fileNameWithPath=C:\mypath\myfile.myextension
call :extractFileNameToVariable "%fileNameWithPath%" fileName
echo %fileName%
goto :EOF

:extractFileNameToVariable
set %2=%~nx1
goto :EOF