WARSAW — Poland’s government carried out a sweeping purge of the Supreme Court on Tuesday night, eroding the judiciary’s independence, escalating a confrontation with the European Union over the rule of law and further dividing this nation. Tens of thousands took to the streets in protest.

Poland was once a beacon for countries struggling to escape the yoke of the Soviet Union and embrace Western democracy. But it is now in league with neighboring nations, like Hungary, whose leaders have turned to authoritarian means to tighten their grip on power, presenting a grave challenge to a European Union already grappling with nationalist, populist and anti-immigrant movements.

The forced retirements of up to 27 of 72 Supreme Court justices, including the top judge, and the creation of a judicial disciplinary chamber were the latest in a series of steps by Poland’s right-wing Law and Justice Party to take over the justice system.

For years, the party has demonized judges as unreconstructed Communists and obstructionists. After coming to power in 2015, it took control of the Constitutional Tribunal, which is tasked with ensuring that laws do not violate the Constitution, and gave authority over the country’s prosecutors to the Ministry of Justice. Most recently, it asserted new powers to select judges. In recent days, judges who have spoken out against the changes have reported being harassed and intimidated.