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.
In "Happy Anniversary," Angel admits to Lorne (then known as "The Host") that he fired his team and severed all ties with them for their own good because the kind of dark territory he was treading would damage them internally and compromise their morality (while he was compromising his), and his mission to bring down Wolfram & Hart would have endangered their lives. So he had to make that he didn't care about them so they wouldn't worry about his well-being and that he'd do something as extreme as letting Darla and Drusilla massacre the Wolfram & Hart lawyers, including Holland Manners, for making Darla a vampire again and ruining his chance of redeeming her. He was willing to allow his team to hate him and consider it a betrayal (and they did, especially Cordelia) just to keep them from getting darker as well and instead stick to the good fight he'd given up on.
Worse, this is all subverted in "Reprise," when An undead Holland Manners revealed the truth about Wolfram & Hart's home office and existence, and Angel realized these actions of his were All for Nothing.
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, they were at war with each other, and unlike the tactics of Earth, the Minbari would return to a crippled ship that was broadcasting for medical assistance. 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."
Later during the Earth Civil War, Sheridan used 30 Shadow-upgraded telepaths to disable 30 Pro-Clark ships in the final battle. Each ship had about 10,000 souls on board and one telepath, when activated, would merge with the ship's computer disabling it. With the ship out of commission, it meant that many would survive the battle. It might cost the telepath his or her life, and they have no choice because the mind was programmed to do this against their will, but Sheridan saw no other way to avoid a costly and bloody battle. He later tells Alfred Bester (high-ranking Psi Cop) giving that order was the hardest thing he has ever had to do, and he took great pains to minimize the grief afterwards by only selecting "orphans": telepaths for whom family could not be located.
In Season 3, Buffy has a dream where she's confronted by Angel, outraged over Buffy killing him to stop the end of the world. A guilt-ridden Buffy can only whimper, "I had to."
Whistler says this in Season 9 regarding his actions in season 8. His plan was to create a better world where good and evil were balanced even if it meant sacrificing a lot of people's lives.
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 Last Great 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 episode "The End of Time" reveals 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." The War Doctor uses this as a justification how he ended the Last Great Time War; "What I did I did without choice; in the name of peace and sanity". It was so antithetical to the nature of the Doctor that subsequent regenerations have disavowed his existence. Note that the Eleventh Doctor does accept that whatever happened really was necessary—just not "in the name of The Doctor".
The trope is the backbone motivation of "The Day of the Doctor". This is where the War Doctor ends the Last Great Time War. The Moment spends the story convincing him that he does not have to do this. In the end, the three Doctors find a third option.
Comes up again in "The Zygon Inversion". In the final confrontation, Bonnie the Zygon tries to blame the Doctor for creating the circumstances that led to the Zygon uprising and all the pain and suffering involved. The Doctor points out that, since she's the one leading the Zygon uprising, she has no small amount of responsibility for what's happened as well. Bonnie invokes this trope, but the Doctor throws it back in her face; both of them felt that what they were doing was necessary at the time, so if she tries to use this to deflect responsibility for her own actions onto others, then so can he.
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!
The show 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.
Jaime also justifies this as his reason for throwing Bran out the window, since it risked exposing him and Cersei, which could lead to their deaths and that of their children.
Ser Alliser Thorne says this about killing Lord-Commander Jon Snow, saying that he's fully aware that he committed an act of treason, but did it for the good of the Night's Watch itself. He even maintains this position just before he and his surviving accomplices are hanged for the murder.
At one point Varys tells Littlefinger "I did what I did for the good of the Realm", and this phrase incidentally sums up how how he justifies everything he does. His eventual friend Tyrion convincingly invokes this notion verbatim to defend Varys before Daenerys.
Grey's 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.
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 (1998): 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 terrible 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.
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?
Stated without any hint of remorse by Gul Darhe'el in "Duet" as he boastfully acknowledges the horrific war crimes that he orchestrated against the Bajorans in the "work camp" that he oversaw and claims that it was the only means of protecting and preserving his empire and his people. This turns out to be an intentionally over-the-top performance; "Darhe'el" is actually Marritza, a filing clerk, who is so traumatized by what he witnessed at the camp and so guilt-ridden by his inability to stop it that he is posing as the late Darhe'el and openly confessing to the acts in the hopes that his subsequent trial and execution will force the Cardassian government to admit to its atrocities.
At the end of the episode "Inter Arma Enin Silent Leges", Admiral Ross uses this as his justification for working with Section 31 to frame a Romulan senator, who was Ross' personal friend, for treason so a Federation mole could take her place. If the senator had remained in place, she would've been willing to sell out the Federation in exchange for a separate, more favorable peace with the Dominion, while the Federation mole would argue for continued support for the war.
Ross: I don't like it. But I've spent the last year and a half of my life ordering young men and young women to die. I like that even less.
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 asking a series of simple questions the captain can't answer.
Maxwell: You know what it's like to be under fire!
One of Castiel's major character flaws is his tendency towards this type of thinking, most notably when he deals with Crowley and betrays just about everyone he knows, which leads to declaring himself God in his power-mad state and devastating Earth and 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 entire reasoning for Sam and Dean whenever they have to do something that is morally reprehensible.
The Arc Words for several episodes of season nine are "I did what I had to." Used by multiple characters as justifications for multiple things, none of them good.
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.
And before that incident, there was the Season 1 episode "Small Worlds", in which Jack prevents the so-called "fairies" from destroying the world by allowing them to take away a perfectly-willing little girl as one of their own, in front of her mother's eyes. Both the mother and the rest of his team are livid towards Jack as a result, with him reasoning "What else could I do?"
In 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: AgentIan Edgerton from his introduction on, makes the tough 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 on Don Eppes, both morally and professionally.
Our Miss Brooks: Averted in the episode "Hobo Jungle". Miss Brooks intends to inform on an honour student who is living with his father (a ruined mechanic) in a hobo encampment, but decides against it giving how devoted they are to one another.
Wayward Pines: Dr. Pilcher predicts that humanity would doom itself in a matter of centuries. His attempts to warn the world community result in him being the laughingstock of the world. Being already wealthy, he starts a project to use cryogenics to preserve the best and the brightest to repopulate the human race about 2000 years later. Unfortunately for him, most refuse his offer, so he uses various methods to kidnap people and freeze them against their will. This also applies to anyone who starts looking at the mysterious disappearances in Wayward Pines, Idaho. Fast-forward to the year 4028, some of the people have been woken up and live in the town, although very few know the truth. Most adults think they were in some sort of car accident and woke up in the town hospital. There are several cardinal rules in Wayward Pines: don't try to leave, don't speak of the past, always answer the phone, etc. Disobeying the rules can result in a public execution. Some of the children are told the truth but are warned to keep it secret even from their parents. Why? Two reasons: 1) Everyone currently living in the town belongs to Group B. Group A was awakened first and were immediately told the truth. After a few months, Despair Event Horizon kicked in, and most committed suicide rather than live with the truth that they are all that's left of human civilization. 2) There are vicious humanoid creatures living outside the massive walls of the town, nicknamed Aberrations or Abbies by Pilcher, what's left of humanity. Unfortunately, Pilcher's policies (including Big Brother-like monitoring) have resulted in a secret group deciding to find a way out no matter the cost, including blowing up a chunk of the wall. Given the second reason stated above, that would be a really bad idea.
The main plot has Snow White and the prince sending their newborn daughter through a portal to another world, to help her escape the Dark Curse. While she grows up into The Chosen One and breaks the curse, she still has huge amounts of resentment from having to grow up without parents. She points out that if they hadn't done "what they had to do", she would have at least grown up happily in a good family instead of being an unwanted foster kid. It's three seasons before she properly comes to terms with these issues.
Snow uses a pragmatic choice to trick Regina into killing Cora, thereby saving Mr Gold and getting rid of a powerful villain. Although this is in fact the best option, Snow suffers My God, What Have I Done? - especially since she manipulated Regina into murdering her own mother. It's established that using this rationale does not excuse one from the consequences. Snow later defies this trope by saying she did what was easy, not what she had to do.
Rumpelstiltskin's master plan involved getting Regina to cast the Dark Curse so he could be reunited with his son. The show never hesitates to point out how (as honorable as his motives were) he effectively ruined countless lives in order to get what he wanted. When he's reunited with his son, the son reacts with disgust at what happened.
Geppetto sent his son Pinocchio through a second portal in order to save him from possibly turning back to wood as the Dark Curse was cast. In this case doing what he 'has to do' is separating a mother from her child, because Snow could have used the second portal to go with Emma and prevent her from growing up as an orphan. In fact, when Geppetto confessed the truth in "Selfless, Brave, and True", Snow is extremely pissed off and punches him in the face for betraying her trust and depriving her of a chance to care for her daughter. It also acts as a Start of Darkness for Pinocchio, since his father still abandoned a young boy to fend for himself.
Played with in the season 6 episode Ill-Boding Patterns. Rumplestiltskin namedrops the trope to justify killing Beowulf to his son. However, although Rumple (deliberately) implied that this trope was in effect, in fact the sentence was literally true - he had been magically commanded to kill Beowulf, and wanted to keep this secret from his son.