Before I get into how I have solved the random shutting down problem most of the times before, I must say that I recommend plugging in the laptop for most of the time. Batteries are not going to last long if you never plug the laptop in. I always plug my laptops in and only unplug them when I have to go somewhere, but once I get near a plug I immediately plug it in again. This is not something that uses little bit of power, it is a computer, and HP batteries can be found online for cheap. Buy a replacement battery if you must, but USE THE PLUG!
I have several HP laptops, and when they get too hot, or when the fans start failing, they always shut themselves down. If the laptop's fan is not working, which is a very common problem for HP laptops, then you can buy a new fan online an replace it, *hire someone to do this for you if you are not technical enough. I was not able to replace the fan on one of my two-year-old HP dv6-7247cl, so I just cannot play videos anymore on this laptop. It no longer shuts itself down unless it is playing video or doing too much work. As long as you keep the CPU below 80% however, it doesn't shut down. This may be your problem, but usually, HP will show a warning screen if there is a problem with the fan when you start it up, and you can press enter to bypass the warning and start the laptop. I used to use an app called SpeedFan to control the fans and this also helped prevent the laptop from overheating.
If your laptop is definitely not overheating, then make sure you have the high-performance Power plan set up, and turn off the option to go to sleep when plugged in. You need to debug what is happening when the laptop shuts down, and also check the task scheduler to make sure you don't have a malicious task that shuts the computer down at a certain time, or after a certain event. You can figure this out and if you try everything and nothing fixes it, return it to HP and demand a return and replace or refund, or a different laptop. Try to avoid refurbished if possible.
I am available if you want more help. send me a message here or contact me jgnetworksecurity at outlook or Gmail. good luck, I dealt with this problem over 20 times but always was able to find solutions