If a pilot's plane suddenly and unintentionally becomes inverted, what is the pilot's best course of action?
What you are describing is Unusual Attitude Recovery (UAR) techniques, which are a standard part of the training for every Private Pilot1

Here is a good description of just such an event.

Almost all pilots do instinctively want to right the plane first, but as I'll explain below, this is a mistake, and the point of UAR training is to change the pilot's instinctive approach.

The actual biggest threat to a plane in an unexpected unusual attitude is speed.   If the plane has too much speed (above VA), sudden control movements can damage the airframe or even break apart the plane.

If the plane has too little speed (stalled or spinning), there may not be effective airflow over the wings and tail, and moving the controls may not do anything at all! (remember, control surfaces need a steady flow of air over them to be effective).

So the very first and most important step in UAR is to manage speed.  Upon recognizing that they are in an unknown and unusual attitude, the pilot's immediate action must be to look at the airspeed indicator:  If its too high (yellow-arc or above), pull the throttle to idle and let the speed come down.  If its too low (white-arc or below), immediately add full throttle and let the speed come back up.

Once the airspeed is anywhere in the green-arc (and precision is not terribly important here, just a manageable speed), then the next steps are to return the plane to roughly level (+/- 10&deg; of pitch), and roll the wings level.



1 I'm unsure if Recreational Pilots and Sport Pilots also get UAR training.