24: Jack Bauer is more or less the personification of this trope. He spends much of the show torturing sometimes innocent people for the purposes of stopping the terrorists. Toward the end of Season 7, he admits that what he's doing often runs counter to the law, but when faced with situations in which innocent lives are threatened, he will do whatever is necessary to save those innocent lives and accept the consequences later.
After the members of Investigations ask Cordelia how she managed to convince Angelus to reveal what he knows about the Beast in "Soulless":
I did what I had to.
An episode later ("Calvary") Gunn gives this, word-for-word, as his justification for killing Fred's former professor.
A few episodes later ("Orpheus") Wesley says this almost exactly as his reasoning for allowing Faith to drug herself, perhaps fatally, in order to capture Angelus.
Then in "Inside Out", Darla's spirit while speaking to Connor uses these words explaining her suicide in order to allow him to live.
And then in "Peace Out", Angel uses it to defend his decision to to prevent world peace in order to preserve free will, at the cost of millions of lives.
Angel: What did you do?! Wesley: What I had to!
However, this is not a perfect example, as his actions were motivated by revenge rather than necessity. Angelowns this trope.
When Angel's reassuring Wesley after Wesley shot and killed what seemed to be his own father in order to save Fred, he realizes aloud that Wesley's always been the one who does what needs to be done, even if it means he alone takes the blame for it. It's at that point that Angel's own lingering grudge against Wesley finally ends.
Pre-series canon shows this was Sheridan's prevailing attitude (which persists) when he destroyed the Minbari Black Star using a trap tactic. The Minbari considered the act cowardly but Sheridan was commanding a crippled ship up against a vastly superior foe, and they were at war with each other. Therefore, he did what he had to do to win the fight, save his ship, and score one for the Humans (his victory is noted as the only time the Earth Alliance scored a win in the Earth-Minbari War).
A strange inversion: When Londo finds Vir drowning his sorrows after assassinating Emperor Cartagia, Londo tries to calm him down a bit not by saying "You Did the Right Thing" but (more or less) "you did what you had to." Recognizing his own bitterness at not being innocent like Vir, Londo tells Vir, more or less, that he can't comfort him, but "it was necessary."
Delenn has to give a "I did what I had to do" justification to G'Kar for her actions in not confirming his story about the shadows, something that eventually led to deaths of millions of his people and the occupation of his home world. She says, "We had to choose between the deaths of millions and the deaths of billions."
Breaking Bad: Walter and Skyler White: "It's over. We're safe." "… Was this you? What happened?" "I won."
Giles: She couldn't take a human life. She's a hero, you see. She's not like us.
Ben: ... us?
Criminal Minds: Used, invoked, played straight, subverted, inverted, and basically an all-around Zig-Zagging Trope, where a character says this of themselves or someone else just about every third episode, with varying justification and effect.
The head of Torchwood being led off to be converted into a Cyberman due to her own actions keeps repeating to herself, "I did my duty for queen and country. Oh God, I did my duty for queen and country!"
The Doctor usually busts out this defense with regards to the Time War that took place between the classic series and the revival. He committed genocide twice over — he wiped out his entire race and destroyed his home planet — in order to end the universe-threatening war and wipe out the Daleks (though it didn't work). Mind you, saying that the Doctor feels bad about his actions is like saying that tsunamis are a bit soggy. That and the Episodes "End of Time" revel he really did have to do it because the Time Lords had become just as dangerous to the universe as the Daleks.
Crops up again in "The Name of the Doctor." John Hurt's character uses this as a justification for unspecified actions so antithetical to the nature of the Doctor that subsequent regenerations have effectively disavowed his existence. Note that the Eleventh Doctor does accept that whatever happened really was necessary—just not "in the name of The Doctor".
Versions of this are something of a staple. Aeryn, John, Noranti, even Scorpius and Crais have reasons to say this at some point. Aeryn definitely had to strike a deal with Crais so D'Argo and John would survive, or the show would have been very short. Noranti exposing untold numbers of people including the crew to the "Hynerian plague" - not so good.
And of course, Crichton holds the entire frelling universe at gunpoint to force an end to a destructive conflict between the Peacekeepers and Scarrans.
Flashpoint: Subverted Trope in one episode, where Parker was torn with guilt that he had pushed the hostage taker too far and indirectly caused them to commit suicide when said hostage taker was going to drop Parker to his death. Ed was quick to say that Parker did everything he could have.
Parker: I killed him, Eddie.
Ed: Greg, he was unwell. He killed himself.
Parker: He was splitting. He set out to slay the monster and I convinced him he was it.
Ed: Greg, he was trying to kill ya. He was trying to kill you. You did what you had to do here, buddy. You did what you had to do!
A Game of Thrones reveals that Jaime Lannister killed the Mad King because the Mad King was trying to destroy King's Landing.
Jaime: First, I killed the pyromancer. And then when the king turned to flee, I drove my sword into his back. "Burn them all," he kept saying. "Burn them all." I don't think he expected to die. He- he meant to... burn with the rest of us and rise again, reborn as a dragon to turn his enemies to ash. I slit his throat to make sure that didn't happen.
Greys Anatomy: This is what Meredith says in the season 7 finale regarding her decision to invalidate Derek's Alzheimer's study by making sure the chief's wife doesn't get the placebo.
Heroes: Jessica in episode 6: "I did what had to be done."
This could practically be the motto of the 5,000 year old Anti-Hero and sometime Trickster Mentor immortal Methos. While certainly not amoral, Methos has lived 5,000 years because almost nothing gets put ahead of the need to survive.
He's also willing to do pretty much whatever it takes to protect his friends, even from their own foolish idealism. For example, when Duncan MacLeod's chivalric ideals won't allow him to kill a rather evil woman he's defeated, after Duncan leaves, Methos walks up to her and introduces himself as "A man who was born long before the age of chivalry." Guess what happens next.
Said about Once an Episode by the lead character when justifying his cruel or illegal behavior.
This is Chase's rationalization for killing President Dibala.
I, Claudius: Livia killed off nearly her entire family, but claims it was all in the name of avoiding another bloody civil war like the one between Antony and Augustus.
Law & Order: Special Victims Unit: This has become something of a Catch Phrase for Elliot Stabler. In one episode, telling an informant "You do whatever you have to do" leads to a lot of trouble. In the Season 8 episode "Clock" when he tells Kathy, "I did what I had to do," she responds sarcastically, "Well, that's refreshing."
Eko is confronted by the Monster (probably), taking the form of his brother, urging him to confess his sins. He faces it and says that he did not sin, because he did only what he had to do to survive. The Monster does not agree with his analysis.
Ben says this verbatim about his purge of the DHARMA Initiative.
In an earlier episode, this is Sawyer's excuse for shooting the Marshal. He says he had to do it because Jack couldn't. Unfortunately, he failed to kill the man and Jack is forced to put him out of his misery.
There's also a large number of things that John Locke did purely because it was "destiny" or because "the Island demanded it".
The Mentalist: In the episode "Blinking Red Light", Jane gives this excuse to Lisbon for why he manipulates serial killer Panzer into talking smack about Red John so Red John kills him, claiming it was the only way to keep Panzer from continuing to kill.
Merlin: Used by Queen Mab. Given that she's fighting not only for her own survival, but the survival of Magic and all the species inextricably connected with it, she admittedly has a point.
Occasionally alluded to by Uther Pendragon in regards to his persecution of magic users.
Very much the case when Merlin poisons Morgana at the end of season 2. It's heartbreaking to watch.
Psych: Invoked in a slightly more lighthearted manner (though surprisingly seriously, considering the show) in a season four episode: through a very complex situation, Shawn has to tell Juliet that he loves her during an investigation—when, in fact, he has no intention of dating her, and is seeing someone else:
Gus: I guess you were just doing what you had to do. Shawn: Yeah, the weird thing is...I think she was about to say it back to me. Gus: I bet she was just playing along. Doing what she had to do.
Charlie has also invoked the trope again since then. Episode 6 had her agreeing to kill a former police officer on a drug lord's behalf in order to save Nora Clayton's life. Luckily, Miles prevented her from actually doing the deed at the last minute.
Jack will sometimes use it to justify his actions. A notable example is in "Menace", when he shoots a Replicator-controlling android that Daniel was trying to talk down and argues that neither of them had any way of knowing whether Daniel was succeeding.
Teal'c takes this stance when he kills Sha're to stop her from killing Daniel even though he feels terribly that he had to do it.
An interesting variation occurs with Teal'c in the season one epiosde "Cor-ai." Teal'c is put on trial for killing an old man during an attack on a planet while he was First Prime of Apophis. It is eventually discovered that the people of the planet flee to caves to hide during Goa'uld attacks but they don't leave anyone behind. When ordered to make an example of one of the citizens (or Apophis would have wiped them all out), Teal'c killed the old man so the rest of them would not be slowed down by him and could escape. But instead of saying I Did What I Had to Do in an attempt to save his own life, Teal'c is ready to take the punishment (death) for his crime.
The point of the episode "In The Pale Moonlight', in which Captain Sisko recalled what he did to bring the Romulans into the war against the Dominion. The episode itself is narrated by Sisko recounting all the morally bankrupt decisions he had to make to forge evidence that the Dominion would invade the Romulan empire.
Sisko: "People are dying out there, every day. Entire worlds are struggling for their freedom. And here I am still worrying about the finer points of morality!"
Sisko: "So... I lied. I cheated. I bribed men to cover the crimes of other men. I am an accessory to murder. But the most damning thing of all... I think I can live with it. And if I had to do it all over again, I would. Garak was right about one thing, a guilty conscience is a small price to pay for the safety of the Alpha Quadrant. So I will learn to live with it. Because I can live with it. I can live with it... Computer, erase that entire personal log."
Colonel Kira has the opinion towards her actions during the Cardassian occupation of Bajor. When attacked by a man, who turned out to have been a dry-cleaner who had been horribly disfigured by one of her explosives meant for a Gul, rather than ask for forgiveness she replies that, as far as she was concerned, all Cardassians on Bajor were part of the occupation, and if he didn't like it, he shouldn't have set foot on their world.
Occurs at the end of the episode "Profit and Loss". Under orders from the Central Command and baited with the promise of revoking his exile if he does it, Garak holds Quark and three dissident Cardassians at gunpoint to execute them. The Gul who gave the orders steps in to take over, insulting Garak's exile as he does so. In response, Garak kills the Gul and helps the dissidents escape. When Quark later asks Garak why he let the dissidents go, Garak merely replies that he did what he had to do... but the audience (and Quark) is left uncertain whether Garak's talking about letting the dissidents go or whether he's talking about the mysterious crime that exiled him from Cardassia.
Quark: "You have to tell me. Why'd you do it? Shoot Toran?"
Garak: "Why did you let Professor Lang go?"
Quark: "I had no choice. I love her."
Garak: "And I love Cardassia which is why I had to do what I did."
Quark: "I don't understand."
Garak: "That's the thing about love. No-one really understands it, do they?"
Star Trek: Enterprise: Captain Archer falls into this during the Xindi arc. In the process of saving Earth, he tortures prisoners, steals a vital component of the warp drive from an alien ship that gets Enterprise moving again but strands the aliens years from their planet, is willing to murder a clone of his best friend, and arguably commits genocide. He himself notes that the justification is wearing a bit thin.
Alien captain: "You're stranding us three years from home! Why are you doing this?"
Captain Archer: "Because I have no choice! Energize!"
When Data has to defend his rights in The Measure Of A Man, Riker (ordered to act as the opposition) does some fairly horrible things, such as removing his hand and turning him off. Afterward (Data wins), Riker feels far too wretched to make this excuse for himself. Data, showing the human virtue of forgiveness, does it for him:
Data: Is it not true that, had you refused to prosecute, Captain Louvois would have ruled summarily against me?
Data: That action injured you, and saved me. I will not forget it.
In another episode, Picard refutes this phrase as a catch-all answer for doing something. Yes, you have to make tough decisions in life, but you need to explain your reasoning for them. When Picard is faced with a Federation captain who's attacking a former enemy out of prejudice, he dismisses the logic by a serious of simple questions the captain can't answer.
Maxwell: You know what it's like to be under fire!
Picard: You weren't under fire.
Maxwell: Lives were at stake!
Picard: Whose lives?
Maxwell:We had to act!
Supernatural: One of Castiel's major character flaws is his tendency towards this type of thinking, most notably when he deals with Crowley, betrays just about everyone he knows, declares himself God, and in his power-mad state causes devastation on Earth and especially in Heaven because he believes it's the only way he can prevent Raphael from winning the civil war in Heaven and restarting the Apocalypse.
The Darach, Jennifer Blake, on Teen Wolf justifies the use of Blood Magic and sacrificing innocent people as being necessary to stop the Alpha Pack, even though the latter group really only seems to be a threat to werewolves and druids, largely leaving ordinary humans alone.
Torchwood: In the series 3 miniseries, titled Children of Earth, Captain Jack Harkness sacrifices his own grandson to save 10% of the world's children/mankind. Of course, this is following the British government's decision forty years earlier to hand over 12 kids to an alien race in order to save their skins.
In the new series Trust Me, I'm A Game Show Host, contestants have to choose between two stories told by the hosts which is the true fact. Almost every time when the contestant chooses the wrong host's answer, the host will say variations of "I didn't want to do it! They made me lie to you!"
''NUMB3RS: Agent Ian Edgerton, from his name onwards, makes the tough, physical calls that Agent Eppes vacillates over. On one occasion he is left alone in a room with the blinds closed to extract vital intel from an uncooperative suspect, a decision which has a lasting impact Don Eppes, both morally and professionally.