Powershell – Specify Credentials to run Powershell Script to Query AD

active-directorycredentialspowershell

I want to run a powershell script to query AD from a machine that is NOT on the domain.

Basically I want to query to see if there is computer account already on the domain for this machine and create it if there is not. Because this has to happen before the machine joins the domain I assume I will need to specify some credentials to enable it to run. (I'm pretty new to Powershell, so apologies if this is a newbie question!)

The script I am using to check the account is below, and then once this has run it will join the domain using the computername specified.

Can you tell me how to specify some domain credentials to run this section of the script as?

Cheers,

Ben

$found=$false
$thisComputer = <SERVICE TAG FROM BIOS>
$ou = [ADSI]"LDAP://OU=My Computer OU,DC=myDomain,DC=com"
foreach ($child in $ou.psbase.Children ) {   
    if ($child.ObjectCategory -like '*computer*') {
        If ($child.Name -eq $thisComputer) {
            $found=$true
        } 
    }
}

If ($found) { <DELETE THE EXISTING ACCOUNT> }

Best Answer

As far as I know, there is no way to pass alternate credentials using the ADSI type accelerator. Two ways you could try to get around this in your code are:

  • have powershell.exe run as the domain user instead of your local user - this will cause everything in the script to use the domain credentials
  • use the Invoke-Command cmdlet, which allows you to pass in a script block to execute, and alternate credentials.

I've never tried either of these, so it will take some trial and error.

Another option that could be more flexible for you is to not use the ADSI type accelerator. There are 2 ways to accomplish this.

  1. Use the .NET framework DirectoryService classes. Here is a good article that walks you through this process. It includes an example using alternate credentials.
  2. Use the Quest Active Directory Management cmdlets. These are wrappers around a lot of AD stuff that make a lot of things easier. They also let you pass in alternate credentials.