We address the fundamental problem of determining the optimal history (regime of operation) of a battery so that the work output is maximum. The essential features of the problem are: (i) the life of the battery is constrained, (ii) the battery has an internal resistance through which it can lose its charge even at open circuit, and (iii) the battery is connected to an electric motor with finite winding resistance. The optimal regime of time-dependent operation is determined based on variational calculus. It is shown that the maximized work output is smaller than the exergy stored initially in the battery, and decreases as the motor resistance increases. The exergy stored in a battery cannot be recovered fully as soon as the resistance of the external circuit is finite, no matter how small.