I'd verify that all fans are freely spinning.... this is a long shot since its not really related to suggestion that plugging in the cord causes it to shutdown, but if a fan doesnt report back that its spinning the system will shut down very quickly in the same symptom. For the fact that it occasionally happens when on battery power only, its possible that on battery power the power management has it running more lightly on lesser power and fans only need to spin slower if at all, and when plugged into the wall the power management is set to 100% for performance and so it ramps the clock to the CPU to the max and expects the fans to spin up to the max if need be and if one of them falls short of spinning at 100% it will shut down.
How long has this problem been happening?