Adding current logged on user to Managed By attribute of computer

Hi, I am in the process of learning PowerShell which impresses me more and more as days go by. My task is to automatically add currently logged on user to Managed By attribute of computer object, where user is currently logged on, in Active Directory. For sure, this can be done with PS script, triggered via GPO as logon or logoff script. Obviously users have to be given right to read/write Managed By attribute of computer object in AD. I have found .vbs script below but I want strictly to use PowerShell script.

How to solve this task?

Set objSysInfo = CreateObject(“ADSystemInfo”)

On Error Resume Next
Set objComputer = GetObject(“LDAP://” & objSysInfo.ComputerName)

objComputer.Put “managedBy”, objSysInfo.Username

There are a couple of ways you could convert that to PowerShell. You could continue to use the ADSystemInfo COM object, which is possible, but kind of a pain. That would look like this:

$sysInfo = New-Object -ComObject ADSystemInfo
$flags = [System.Reflection.BindingFlags]::GetProperty

$userDN = $sysInfo.GetType().InvokeMember('UserName', $flags, $null, $sysInfo, $null, $null)
$computerDN = $sysInfo.GetType().InvokeMember('ComputerName', $flags, $null, $sysInfo, $null, $null)

At which point you have your two Distinguished Names in variables, and you can update the managedBy field in AD using whatever PowerShell method you prefer (AD cmdlets, Quest AD cmdlets, ADSI, whatever.)

Alternatively, you could identify the user and computer in other ways. This approach should work in a single-domain scenario, but I’m not sure if you’d run into trouble if multiple domains are involved. This example assumes the use of the Microsoft AD cmdlets:

$mySid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User

$userAccount = Get-ADUser -Identity $mySid.Value
Set-ADComputer -Identity $env:COMPUTERNAME -ManagedBy $userAccount

Edit: If for some reason Set-ADComputer can’t find the computer account based on $env:COMPUTERNAME alone (which shouldn’t be a problem, as far as I know), you can check Win32_ComputerSystem for your domain name and send that along to the -Server parameter of Set-ADComputer.

I used this PowerShell script:

$searcher = new-object System.DirectoryServices.DirectorySearcher
$find = $searcher.FindOne()
$thispc = $find.GetDirectoryEntry()

$find = $searcher.FindOne()
$me = $find.GetDirectoryEntry()


It works when I execute script locally on Windows 8.1 using PowerShell ISE, Managed By attribute of that computer is populated with DN of logged user. But nothing happens when user logs on, gpresult /r shows that GPO is applied but Managed By attribute stays empty. I used script as logon script deployed using GPO.

I have to be patient, after some time Managed By attribute was populated with logged on user DN. Great!!!