Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Move Computer to a different OU without AD cmdlets using PowerShell

$
0
0

Hello.  Struggling with understanding [ADSI] yet again.  Just when I think I get it, I don't.  

So I wrote this PowerShell code yesterday which moves a Computer from the ComputersOU to the OU I specify. 

$CN = $env:COMPUTERNAME

$root = [ADSI]'' $searcher = New-Object System.DirectoryServices.DirectorySearcher($root) $searcher.filter = "(&(objectclass=computer)(cn= $CN))" $name = $searcher.findall() # Get the DN of the object $computerDN = $name.Properties.Item("DistinguishedName") # Connect to the computer object $Object = [ADSI]"LDAP://$ComputerDN" # Specify the target OU $TargetOU = "OU=VDI,OU=ComputersWB,DC=BLAIRNET,DC=NET" $TargetOU="LDAP://$TargetOU" # Move the object to the target OU $Object.psbase.MoveTo($TargetOU)

It works when I am logged in.  However I have rights everywhere.  I need this to work using credentials as i keep getting the Access is Denied error.  

I tried this code when logged in as the no rights user:

$CN = $env:COMPUTERNAME
$domain = "BLAIRNET"
$un = (Get-Content '\\secret2\LIBRARY\Powershell\PSScripts\Private\id.txt')
$username = ($domain + "\" +$un)
$password = (Get-Content '\\secret2\LIBRARY\Powershell\PSScripts\Private\pw.txt')

$root = [ADSI]''
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectclass=computer)(cn= $CN))"
$name = $searcher.findall() 


# Get the DN of the object
$computerDN = $name.Properties.Item("DistinguishedName")

# Connect to the computer object
##$Object = [ADSI]"LDAP://$ComputerDN",$username,$password
$Object = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$computerDN", $username, $password)

# Specify the target OU
$TargetOU = "OU=VDI,OU=ComputersWB,DC=BLAIRNET,DC=NET"
$TargetOU="LDAP://$TargetOU"

# Move the object to the target OU
$Object.psbase.MoveTo($TargetOU)

The error I continue to get is Exception calling MoveTo" with 1 argument(s): "Access is denied".  

Can anyone out there assist me in getting this written with credentials somehow?  


Matt Dillon


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>