Hopefully easy > Computer Name from User Name (distinguishedName)

Want to get the Computer name of the User (User account I know).

Hoping this makes sense below:

$User = Read-Host "Whats the Account UserName?"
#1. input Username credentials
get-aduser $User | Select-Object DistinguishedName
#2. get the distinguishedname for the user account
Get-ADComputer -Filter {ManagedBy -eq 'CN=xsurname, xfirst,OU=CG,OU=PROD,OU=BusinessUnits,DC=ourbusiness,DC=com,DC=au'
# 3. need to drop 'DistinguishedName" from 2. into the 3.  [ManagedBy -eq {ManagedBy -eq 'xx....xxx'        variable.

#How can I ‘define’ this as what the error is?

 

Thanks in advance for this one - will save me plenty of time.

Simon, welcome to Powershell.org. Please take a moment and read the very first post on top of the list of this forum: Read Me Before Posting! You’ll be Glad You Did!.

When you post code, error messages, sample data or console output format it as code, please.
In the “Text” view you can use the code tags “CODE”, in the “Visual” view you can use the format template “Preformatted”. You can go back edit your post and fix the formatting - you don’t have to create a new one.
Thanks in advance.

So you have to save the result of Get-ADUser in a variable and use it for the filter for Get-ADComputer.

What do you mean with that? What Error?

The following should work:

$DN = $null # Clear out variable DN
$user = Read-Host "What is the account username?"
# -Expand returns the property value rather than an object containing the property
$DN = Get-ADUser $user | Select-Object -Expand DistinguishedName # DN contains just the DistinguishedName
Get-ADComputer -Filter 'ManagedBy -eq $DN'

@AdminOfThings45 && Thanks for the feedback and working answer.

Most important thanks for the explanation and notes - learning for the day.

The script above does exactly as requested. Initially a few time outs however still produced result.

 

For anyone else I added a new first line to the above to assist in my environment:

Import-Module ActiveDirectory

 

Top of the day to you.

 

[quote quote=247345]For anyone else I added a new first line to the above to assist in my environment:

Import-Module ActiveDirectory[/quote]

Since Powershell version 3 that’s unnecessary. A properly installed module will be imported automatically by Powershell if needed.