Numbers 31:17

Now therefore kill every male among the little ones, and kill every woman that hath known man by lying with him.

The command was given by Moses to the men of war as a rebuke to the officers for sparing the Midianite captives after Israel had slain the Midianite males in battle and taken the women and children captive. It ordered the death of every male among the little ones and every woman who had known a man by lying with him, singling out the captive women as the most guilty and dangerous enemies of Israel. The Midianites were to be punished because they had enticed Israel into sin and helped lead them into idolatry. The women were held responsible for causing Israel to commit trespass against the Lord in the matter of Peor, which brought a plague upon the congregation that killed 24,000 Israelites.

The women acted through the counsel of Balaam, who sold and betrayed Israel for Balak's reward and promotion. He gained the favor of the Midianites at the cost of the 24,000 Israelites, and then perished and died with the Midianites. Preserving the idolatrous, sexually immoral women as captives would have kept Israel's morals at continued risk. The killing was God's judgment and punishment of a wicked nation that had vexed Israel and seduced them from God. It was carried out by Israel acting as God's instrument and as instruments of His wrath motivated by zeal for His glory, not as permission for personal revenge.

The Midianites had rebelled against God's authority, trampled His law, bowed to images of wood and stone and silver and gold made by their own hands, and taught their children that those idols gave life and health and fruitful lands and riches and honor. They scorned the God of Israel, despised His people because their works were righteous, vexed Israel and seduced them into idolatry, and after long forbearance filled up the measure of their iniquity, so God brought swift destruction upon them. The command contains no cruelty and no injustice, because God as Maker and Ruler of the world has authority to judge sin, has unlimited control and right to do as He pleases with the work of His hands, and appoints agents to carry out His judgments. Human beings should not presume to measure His justice by their limited wisdom. The verse warns against sympathy that excuses sin or shields those who lead others into wrongdoing.