I'm tring to run Powercli script from VM that have all the modules nedded. The script should insert other VM to domain.
$ScriptText ="Add-Computer -DomainName foofoo.com -DomainCredential " + $DomainC +" -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'"
echo $Script
Invoke-VMScript -vm $VMName -GuestCredential $AdminC -ScriptText $ScriptText
all the variables inserted correctly.
runing
Add-Computer -DomainName foofoo.com -DomainCredential $DomainC -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
from the other vm poweshell console is running well and the output message WARNING: The changes will take effect after you restart the computer ..
$Script return:
Add-Computer -DomainName foofoo.com -DomainCredential System.Net.NetworkCredential -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
but after that this script stuck and I have no error or other output.
Any idea what is the reason for that ?
The Add-Computer CMDlet takes a credential object for the domain credential parameter. By trying to convert that to a string in your $scripttext variable - you're losing the credential type in the conversion. You need to make a credential object inside your script text rather than passing in a variable containing the credential object. This adds some complexity because you generally want to pull a password from a secure vault. The below examples shows how to include the password as a plain text - but this isn't really advised for obvious reasons.
$scripttext = @'
$user = "UserName"
$password = ConvertTo-SecureString "bar" -AsPlainText -Force
$DomainC = New-Object PSCredential $user, $password
Add-Computer -DomainName foofoo.com -DomainCredential $DomainC -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
'@
Invoke-VMScript -vm $VMName -GuestCredential $AdminC -ScriptText $ScriptText