In this episode, Alexander convinces his father, Worf, to accompany him on a trip to the "ancient west" on the holodeck. Worf reluctantly plays the part of sheriff in the town of Deadwood. Alexander is his deputy, and Troi (whose father was fond of tales of the Old West) enthusiastically plays "the mysterious stranger".
Meanwhile, Data and Geordi experiment with using Data's brain as a backup for the Enterprise's computer. A seemingly small malfunction occurs. Soon, Data's programming begins to take over parts of the Enterprise's computer, replicating what is stored in his memory. Data's poetry overwrites Crusher's stage-play lines, and Picard's music is overwritten by Data's.
In the holodeck, Worf has apprehended Eli Hollander, a cowboy accused of murder. Eli's father Frank has come to rescue him from jail, and kidnaps Alexander to use as bait. Frank, however, looks and sounds exactly like Data. At first Worf assumed that Data had been invited by Troi or Alexander to play the role of Frank. But it soon becomes apparent to Worf that something is seriously wrong when he is shot. By this time Worf and Troi have discovered that they cannot end the program, and the holodeck's safety features are off. Also, the holodeck is replacing all the characters with replicas of Data, and Troi discovers that not only do the characters appear to look like Data, they also have his strength, speed and reflexes. However, they realize if they can ride the story to its end, the program will terminate on its own. To that end, Worf and Troi make a deal with Frank: Eli will be exchanged for Alexander.
Worf thinks everything is settled, but Troi knows better - the outlaws are not concerned with honor, and they will certainly try to kill them. They construct a shield to protect Worf from bullets. During the shootout, the outlaws are defeated, but the program does not end until Data, in the character of an enamored woman, throws herself into Worf's arms. Finally, the program ends, much to Worf's relief.
Geordi determines the cause of the malfunctions aboard ship and fixes them. In their quarters, Alexander asks his father if he will ever want to visit Deadwood again, and smiles when Worf replies, "The town of Deadwood may face danger again. If they do, they will need a sheriff... and a deputy."