You will need a memory element such as a relay to hold the current direction of the motor.
simulate this circuit – Schematic created using CircuitLab
Here a DPDT relay and two microswitches are used. The motor M1 drives to the "left" when the top terminal is positive and to the right when the top terminal is negative.
Suppose the relay is dropped out. The top terminal is positive, SW2 and SW3 are in the positions shown. When the motor reaches the left limit, SW2 is actuated, energizing the relay. The motor immediately reverses, but the top contact has pulled in, keeping the relay energized through D2. The motor operates until SW3 is actuated, which interrupts current to the relay (D3 catches the flyback voltage). The relay drops out, releasing the hold contact and it remains dropped out, and we're back where we started.
Interrupt V1 to switch everything off (and it will always drive to the left when power is applied). Interrupt only the current to M1 and the memory of the previous direction will be maintained as long as V1 is applied (which means continuous draw if the relay is energized).
A solid-state solution could use a single CMOS gate package (eg. 1/2 a CD4011B) and a MOSFET H-bridge to drive the motor:
simulate this circuit
Initial condition: no relays energized. One set of RY2's direct power one direction to the motor.
Second condition: SW2 triggered, its NO contact energizes RY2, which reverses motor polarity and latches itself (you'll need a pair of diodes or another relay contact set to accomplish both reversal and latching).
Third condition: SW2 released, RY2 is still latched, mechanism swings the opposite direction.
Fourth condition: SW1 triggered, its NO contact energizes RY1. An NC contact set on RY1 breaks RY2's latching circuit, and the same NO contact latches RY1 on until power drops away. The second RY1 contact set's NC interrupts power to the motor.
EDIT: Here's what I have in mind:
Best Answer
What you want is a double-pole double-throw (DPDT) switch. These can be arranged to appear as a box that has two inputs, and the outputs are the inputs but possibly flipped depending on the state of the switch. Hook up the DPDT switch like this:
Follow this circuit and see that when the switch is in the right position, as show, OUT is directly connected to IN with the same polarity. When the switch is in the left position, OUT is flipped from in.
If IN is connected to a power supply and OUT to a DC motor, then the switch sets the direction the motor is driven by the applied voltage.
This switch can just as well be the output of a DPDT mechanical relay. Energizing or not energizing the coil then controls the motor polarity. Your microswitch can drive this relay on/off, or it can be the input to a microcontroller. The micro can then perform more complicated logic and timing on the microswitch signal and drive the DPDT relay accordingly.