I so love this episode, for what's implied. When Barclay is called to look into the holodeck glitch, he tracks it to the protected memory that Moriarty is stored in. Subsequent to activating his program, & a brief conversation, he returns him to stored memory, after which he immediately reappears, on his own, left inside with the holodeck computer, free to craft his ruse.
He testified to having experienced brief moments of consciousness, over the 4 years. It's likely he was existing somehow inside the programs, where his disembodied presence was able to affect or alter them. Moriarty, himself is responsible for the wrong-handed glitch, his own presence corrupting the memory files, very likely deliberately, for the purpose of specifically ruining a Holmes mystery & getting someone to investigate the issue & do exactly what Barclay did, activate him.
In 4 years of worming his way around the 2D plane of the ship's memory, he found a way his program could corrupt it, & then developed that into being able to control his own program, once it was active again. He planned while trapped in there, 1st to infect the Sherlock Holmes programs with a glitch, 2nd to gain access to his own program, & 3rd to gain control of the whole holodeck again, which he could use to blackmail the crew again, by gaining control of the ship
This time, instead of threatening the ship with damage, like before, he knew he had to make them work on the solution to his dilemma, & that was his Achilles heel. He still needed their help. This necessitated he move quickly, once he was active, & thereby likely didn't have time to correct or deactivate the wrong-handed glitch, which became his plan's Persian Flaw.
Ultimately, Pulaski missed out on getting proved wrong. Data spotting that the glitch was still happening meant he did in fact best Moriarty. However, just as importantly, Moriarty proved himself right also, in that even without his form, existing as just data, he could still think, & therefore he still existed (I think therefore I am)
I'd even wager that the continued use of the Sherlock Holmes programs by Geordi & Data is what gave Moriarty those brief, periods of consciousness without substance, while the parent program was in use. Had they never returned to play Holmes & Watson, after Elementary, Dear Data, he might've never been freed.