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> }
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:
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.
DirectoryService
classes. Here is a good article that walks you through this process. It includes an example using alternate credentials.Sorry - this should be a comment really, not an answer, but I wanted to post the working code in case it is of use to anoyone else.
MattB was bang on the money! Got the following working:
Now I've proved the concept, will encrypt the password to make it a little more secure.
Thanks for your help!
You can continue to use the [ADSI] accelerator and pass credentials by adding the following line:
Get-Credential
This should be one of the first things in your script. In my own environment I needed to write a script to connect to a different domain. With that different domain I had different credentials, so writing the following allowed me to do what I needed to do:
Get-Credential Import-csv test.csv | foreach { $ou = [ADSI]"LDAP://ou=users,dc=test,dc=com" $newuser = $ou.Create("User", "cn=$name" $newuser.SetInfo()
I understand that the above code was used to create a user, but the concept should hold true for any other action
Doesn't appear that you still need it, but here is a link about how to create a PowerShell credential.