Using Powershell to move Computers to and from an OU.

Hello all,

This next question I have has me stumped so please forgive me if I haven't explained myself correctly.

In our AD structure we have multiple OUs for users and Computers based at different sites. We have different GPOs for each OU so it is important that the computers are in the correct OU..... but they are not!

I am trying to use powershell to identify the DistinguishedName of the users last logged on to the computer and then hoping to use that as a variable to move the computer to the correct OU. The users being in the correct OU is probably the most accurate so using that instead of anything else like IP Addresses

I'm sure there is a much easier way of doing this so please advise.

My script so far :
$computer = Hostname
$lastlogged = Get-ChildItem "\\$Hostname\c$\Users" | Sort-Object LastWriteTime -Descending | Select-Object Name -first 1 | Select Name -ExpandProperty Name
$user = Get-ADUser -Identity $lastlogged | Select-Object DistinguishedName | Select Name -ExpandProperty DistinguishedName

This will out put like this - CN=Joe Clough,OU=Users,OU=IT,OU=Manchester,OU=Corporate,OU=Service Delivery,DC=Domain,

The Computers OU is in the same OU as the USERs so I need to find a way to remove the CN=username, OU=Users and move that users computer to OU=Computers,OU=IT,OU=Manchester,OU=Corporate,OU=Service Delivery,DC=Domain,
Joe CloughAsked:
Who is Participating?
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Generating the new OU is easy.
$user -replace 'CN=.*,OU=Users,', 'OU=Computers'
Get-ADComputer $computer | Move-ADJobject -TargetPath ($user -replace 'CN=.*,OU=Users,', 'OU=Computers')

Open in new window

Joe CloughAuthor Commented:
Following from the above.

If I can run the script to all computers in an OU to obtain the IP address, if you IP address = (forexample) it will move to an OU that I have already set as a variable like $ = OU=Computers,OU=IT,OU=Manchester,OU=Corporate,OU=Service Delivery,DC=Domain,

Its just getting all that information first to then set as a variable which I am having the problem with.
PberSolutions ArchitectCommented:
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

-- Qlemo (https:#a42413045)
-- Joe Clough (https:#a42413009)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

Experts-Exchange Cleanup Volunteer
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.