In the episode Equinox Part II, the EMH is operating on Seven of Nine, his ethical subroutines having been deleted. Shortly after, he appears on Voyager — presumably after being beamed over by Equinox's captain — and switches sides again. Why does this happen?
Equinox was one of the few episodes of Voyager to receive an official novelisation, in this case written by Diane Carey (who also novelised VOY: Endgame). In it we learn that before beaming the crew over to the Voyager, Captain Ransom downloaded the EMH's program from sickbay and put it onto a cartridge, with the ethical subroutines restored, which he gave to Marla Gilmore to give to Janeway to upload, presumably after they'd scanned it and found his program intact.
As Gilmore did as she was told, Ransom moved to another station. "Computer, give me access to the shield grid."
It worked. The computer was still functioning under the assumption that he was in command.
"Marla," he called at the last second, "here."
He tossed her a remote computer cartridge, especially encoded.
"That's Captain Janeway's doctor, with his ethical subroutines restored. When you get to Voyager, tell her the doctor over there is ours. Have her upload him back into their system. Her own EMH will be able to take back his sickbay."