"And Moses said to them, “Have you spared all the women? 16 “Behold, these caused the sons of Israel, through the counsel of Balaam, to trespass against the Lord in the matter of Peor, so the plague was among the congregation of the Lord. 17 “Now therefore, kill every male among the little ones, and kill every woman who has known man intimately. 18 “But all the girls who have not known man intimately, spare for yourselves." (Numbers 31:15-18).
The harsh command is what God told Moses to do. "Take full vengeance for the sons of Israel on the Midianites . . . " (Num. 31:2). But why would God order this and even have children killed?
In Numbers 24 the people of Israel had played the harlot with the daughters of Moab and served Baal, a false god. But this idolatry, though bad enough, was accompanied by the pagan and licentious practices of the pagan women who were seducing the people of God. This would ultimately result in the destruction of Israel as well as the destruction of the messianic line.
God is often so strong in the Old Testament--even ordering the killing of people so that he might ensure that the future messianic line would remain intact. The enemy, Satan, began his attempt to destroy God's people in the Garden of Eden by also trying to corrupt the world (which led to Noah's Flood), by trying to destroy Israel with attacking armies, and by encouraging Israel to fall into idolatry by exposure to other cultures as well as intermarrying women from those cultures. The result of both the idolatry and the interbreeding would have been the failure of the prophecies that foretold of the coming Messiah which specified which family line the Messiah would come through. The Messiah, Jesus, would be the one who would die for the sins of the world; and without that, death there would be no atonement. Without the atonement, all people would be lost. So, God was ensuring the arrival of the Messiah via the destruction of the ungodly.
This is why God ordered the destruction of this nation. It was pagan, participated in vile and grotesque sins, was idolatrous, and was posing a serious threat to the national identity and sanctity of Israel.