Invoke-VMScript passing credentials to Add-Computer cmdlet

We have this really cool process within our storage where we can move over a list of VM’s to a test environment and then remove the form the domain and add them to the test domain.

The problem I am running into is when I use Invoke-VMScript to pass the commands to the servers to remove them from the existing domain and then to add them to the new domain, I need credentials to joint them to the new domain. The reason this is a problem is because I can’t figure out how to construct the credential on the host side so they can be used by PowerShell to use in the Add-Computer cmdlet.

I am working on getting it working with a netdom command, but I would prefer figuring it out in PowerShell.

netdom join %computername% /Domain:a.local /UserD:me /PasswordD:pw /REBoot

Making progress here, but I wonder if there is a way to do this without having to pass a user name and password in the script?

$cmd4 = @'
$password = 'pw' | ConvertTo-SecureString -asPlainText -Force
$username = 'dom\me' 
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -ComputerName $(hostname) -Credential $credential -DomainName 'dom.com' -Restart 
'@
$paramInvoke = @{
    VM = $namefull
    GuestCredential = $CredLocal
    ScriptType = 'Powershell'
    ScriptText = $cmd4
    Server = $viServerTst
}

    Invoke-VMScript @paramInvoke

One more thing that was of concern was the fact that the severs would not have access to their previous domain, would I need credentials and connectivity to change them to work group. If you don’t use the UnjoinDomainCredential parameter, you CAN remove it from the domain with this code.

$cmd5 = 'Remove-Computer -WorkgroupName `"workgroup`" -Force -Restart -Confirm:$false'