There isnt much way, Get-ADDomainController -Discover is the comdlet you would need to use, it use the DCLocator method to find a Domain Controller, but how you will manage the -Credential part ? as you can't run the powerscript against a DC from a workgroup computer as the process is run within the netlogon's process.
You would maybe need to try to join the domain if it fail, then act accordingly.
$result = Add-Computer -DomainName "myDomain" -ErrorAction SilentlyContinue -ErrorVariable ComputerError
Write-Host $ComputerError[0]
Your script might need a lot of work as for other computer you need to point the DNS's server of the other server to that newly DC to have the Get-ADDomainController & Add-Computer cmdlet to work out.
Be aware that you can have multiple DC in the same LAN, the only difference to what DC answer what workstation is the DNS set inside the network adapter of the workstation to be able to use the correct's one.