The music star wore a black wool fur cape and a long black skirt, and put on black sunglasses once the short hearing had finished.
The court was told that under the terms of their custody arrangement, Rocco was to live with his mother in New York but he now seems to have changed his mind.
Mr Ritchie's lawyer Eric Buckley said of Rocco: "He has expressed very clearly that he does not want to return to New York". Madonna looked as if she wanted to talk but was calmed down by her lawyer.
In an apparent reference to Mr Ritchie, Justice Kaplan said: "Has he prevented the child from returning to the US?" Mr Buckley replied: "Effectively yes".
The judge said Rocco should talk to his mother and then decide which of his parents he wants to live with. He will get his own court-appointed lawyer but will have to come back to New York first, the New York Daily News reported.
The judge told Madonna: "I'm granting you all the relief you have requested", eliciting a smile from the singer.
Justice Kaplan added: "I'm directing the child to be returned to New York. If he wants to stay with his father, he must return to his mother."
Justice Kaplan also told the couple not to talk to their son about the legal issues of the case.
After the hearing, Madonna was escorted out of the court by a security guard and declined to comment. Her lawyer Eleanor Alter said: "We don't discuss ongoing cases with the press, but particularly when there is a minor child".
The couple's adopted son David Banda, ten, was not mentioned in the court hearing.
Nobody representing Mr Ritchie or Mr Buckley was available for comment.
Madonna and film director Mr Ritchie were married in 2000 in Skibo Castle in Scotland in a high-profile ceremony.
Under the terms of their divorce, he reportedly received assets worth around £50 million (NZ$109.51 mill) including a pub and estate in Wiltshire.
Madonna has occasionally spoken of her marriage and told Newsweek that the romance died, leaving her wondering if true love had even existed.
In another interview this year, she said that at times she "felt incarcerated" by Mr Ritchie.
She added: "If you're an artist you've got to find someone who accepts who you are and are comfortable with that."
Mr Ritchie has been far more vocal about their relationship. He has said that while he does not regret his time with Madonna, the drama was too much and that their life became a "soap opera".
Friends of his have also claimed that her strict diet, her Kabbalah religion and obsession with yoga made her hard to live with.
After the break-up Madonna, who has four children, began dating dancer Brahim Zaibat, 29 years her junior, but they later split up.
Mr Ritchie, who was behind films including The Man From U.N.C.L.E. and Sherlock Holmes, began dating model Jacqui Ainsley, 34. They have three children and were married in July.
Madonna regularly posts pictures of Rocco on Instagram but admitted he was not interested in performing with her.