Excluding non-essential text from AD query

Hello,

When I run the following cmdlet:

Get-ADComputer -Filter * -SearchBase “CN=Computers, DC=companyname, DC=net” | Select Name

I get the following result where it just shows the computer name as desired:

acomputername

However, if I use the script below, I get this format instead:

@{Name=acomputername}

So how do I go about excluding the @{Name=} portion from the computer name?

Sorry for the formatting, I wasn’t sure where to put the code in the Tools-><> Source Code option in relation to the <P>s.

$test = Get-ADComputer -Filter * -SearchBase “CN=Computers, DC=companyname, DC=net” | Select Name

foreach($line in $test) {
if($line -match $regex){
write-host $line
}
}

Use the -ExpandProperty parameter with Select-Object.

 

When you run commands in PowerShell like Get-ADComputer it returns objects. While a text representation of those objects are displayed on the screen, that is just a representation not the full object. In your first case you piped the objects to Select-Object and specifically asked for the Name property of the object although there are many other properties available. Instead of piping to Select-Object, pipe the output to Get-Member and you can see all the available properties for the objects it returns. I suspect you want to filter the results based on the name property and a regular expression. In your foreach loop however, you are comparing the entire object (even though at this point it only has a name property since that is what you selected) against the regular expression. You would need to de-reference the object with the dot operator ($line.name -match $regex). Just to make things a little cleaner, I would write it this way:

Get-ADComputer -Filter * -SearchBase “CN=Computers, DC=companyname, DC=net” |
    Where-Object {$_.name -match $regex} |
        Select-Object -ExpandProperty Name

 

 

[quote quote=269141]Use the -ExpandProperty parameter with Select-Object.

[/quote]
Looks like Matt beat me to the punch. ExpandProperty will work as because instead of returning a custom object with a Name property that you would have to reference with the property de-reference operator (dot), it will return just the string value of that property.

Thanks for the responses from all of you. That addressed my question perfectly.

the other approach depending on what you’re doing with the data in the end, or if you need to use multiple values out of the results.
$line.name

or if you are trying to use it in some strings you can do $($line.name)