The script works well with one exception. If your logical name for the database files contains spaces, it will cause issues.
If you alter the stored procedure and enclose the logical name for the database file in double quotes, this fixes the issue. See below:
set @sql = 'ALTER DATABASE ' + @DbName + ' MODIFY FILE (NAME = "' + @LogicalName + '", FILENAME = "' + @NewPath + '")'