Search code examples
powershellscriptingactive-directoryouorganizational-unit

Changing hostname and domain joining fine; but when specifying OU


So when I run the following script it works as expected

$newname = Read-Host 'Desired hostname'
$user = Read-Host 'Domain admin username'
$cpc = hostname.exe
Add-Computer -DomainName DOMAIN.CO.UK -ComputerName $cpc -NewName $newname -Credential domain\$user
pause

However when I then attempt to add -OUPath "OU=ourou,OU=ourou,DC=domain,DC=co,DC=uk" like so:

$newname = Read-Host 'Desired hostname'
$user = Read-Host 'Domain admin username'
$cpc = hostname.exe
Add-Computer -DomainName DOMAIN.CO.UK -ComputerName $cpc -NewName $newname -Credential domain\$user -OUPath "OU=Workstations,OU=Windows 10,DC=domain,DC=co,DC=uk"
pause

The script breaks, returning:

failed to join domain from its current workgroup... the system cannot find the file specified

Any ideas?

Here's the AD layout, in case I'm making a silly mistake:

AD OU structure


Solution

  • In case anyone runs in to the same problem, I've now figured out that I was in fact making a silly mistake.

    the -OUPath command works backwards through OU trees. So in my example, I wanted to reference the OU: domain.co.uk\Workstations\Windows 10

    Originally my code was: -OUPath "OU=Workstations,OU=Windows 10,DC=domain,DC=co,DC=uk"

    The code I needed was: -OUPath "OU=Windows 10,OU=Workstations,DC=domain,DC=co,DC=uk"

    Hopefully I've explained that well enough.