WASHINGTON—President Trump ordered a rapid withdrawal of all U.S. military forces from Syria, officials said Wednesday, marking an abrupt shift of the U.S.’s posture in the Middle East.

The U.S. immediately began moving a handful of personnel from Syria and will quickly extract about 2,000 forces over the next few weeks, officials said, ending a four-year military campaign against Islamic State on the brink of its defeat.

“The Pentagon has an order to move troops out of Syria as quickly as possible,” a U.S. official said.

The decision recasts U.S. policy in the Middle East, where the Trump administration has been working to defeat Islamic State, contain Iran’s expansionist ambitions and counter Russia’s influence in Syria, where Moscow has a vital Navy base. The planned exit also worried the U.S.’s Kurdish partners, who risk losing vital backing just when Turkey is threatening to attack them.

The U.S. has long said it would remain in Syria until Islamic State was defeated and local forces could prevent a new rise of extremist forces, and to press Iran to withdraw its forces from the country. While those objectives haven't been met, Mr. Trump declared an end to the fight against Islamic State, or ISIS, in a tweet on Wednesday.