WASHINGTON — Stuffed by their captors into the back of a car with their children as they were being ferried across the rugged tribal areas of northwest Pakistan, an American woman and her Canadian husband were in the final moments of their five-year ordeal as hostages.

But suddenly, shooting erupted. One of their abductors, a Taliban-linked militant, shouted, “Kill the hostages.”

The militants found themselves cornered by Pakistani troops. The gun battle ended, and soldiers pulled the family from the vehicle, to be taken by helicopter to Islamabad. They were safe. The Pakistanis, acting on information provided by American intelligence and collected from drones that had been tracking the hostages, had pulled off Wednesday’s risky operation.

The brief firefight, described by relatives of the family as well as American, Canadian and Pakistani officials, capped the end of an unimaginable ordeal for Caitlan Coleman, 31, and her husband, Joshua Boyle, 34, who were seized in October 2012 by the Haqqani network, a Taliban faction. Ms. Coleman, who had been pregnant when she was abducted, gave birth to all three of her children in captivity. Mr. Boyle suffered minor shrapnel wounds in the raid, his family said.