Couple of notes –
Avoid replying to your own posts; a lot of us look for “unanswered posts” and by replying, you come off that list and don’t get noticed.
Consider attaching (as a TXT file) long scripts like that. It’s a bit much to digest in a web page.
In terms of fixing the orphaned users, that’s more a SQL question. Are you asking for the relevant T-SQL query, or how to execute that from PowerShell?