Hello,
I've tested your script and I got the same issue, so I modified your script
Below the script modified
$userPassword = Read-Host -AsSecureString
$stringObject = ConvertFrom-SecureString $userPassword
$stringObject | Set-Content -Path <yourpath>
$userName = <yourusername>
$pw = Get-Content <yourpath>
$securePW = ConvertTo-SecureString -String $pw
$plainCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($userName, $securePW)
Remove-Computer -UnjoinDomainCredential $plainCred -PassThru -Force -WorkgroupName "WORKGROUP"
The error message was different, it was access denied, so I've tried with a domain account instead of a local account and it worked.
I suppose this command works only with a domain account because this cmdlet try to disable the computer account in Active Directory and a local user does not have the right to do it.
If you want to automate the process you should create a service account with the local admin right on your computers and rights on the computer objects in your Active Directory
Best Regards,