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,DC=.com
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,DC=.com