Link to home
Start Free TrialLog in
Avatar of YZlat
YZlatFlag for United States of America

asked on

Converting AD object to a string with Powershell

I am trying to retrieve a list of operating systems from all the machines in a particular OU and there is a space after each OS name and i wanted to use TrimEnd to remove it. I don't want to use Replace in case OS name contains a space in the middle.

$ou = [ADSI]"LDAP://OU=My OU,OU=My Group,DC=MyDomain,DC=com"
$alComputers=new-object Collections.ArrayList

foreach ($item in $alComputers){
	#Write-Host $item.name
	$os = $item.operatingsystem.TrimEnd(" ")

}

Open in new window


I keep getting an error in this line:

$os = $item.operatingsystem.TrimEnd(" ")

What am I doing wrong? I assume $item.operatingsystem is not a string but an object, so what can I do to convert it to a string?
Avatar of soostibi
soostibi
Flag of Hungary image

The code is not correct, here is a working one.
But I do not see any extra space at the end of the name of the operating systems.

But in case you have, replace line 6 to:
$item.operatingsystem.tostring().trimend()
$ou = [ADSI]"LDAP://OU=My OU,OU=My Group,DC=MyDomain,DC=com"  
$alComputers=$ou.psbase.children
  
foreach ($item in $alComputers){  
        # Write-Host $item.name  
        $item.operatingsystem  
}

Open in new window

Avatar of YZlat

ASKER

$os=$item.operatingsystem.tostring().trimend()

worked for me, but also

$os = $item.operatingsystem[0].trimend()

What is the difference between  $item.operatingsystem and $item.operatingsystem[0]?

ASKER CERTIFIED SOLUTION
Avatar of soostibi
soostibi
Flag of Hungary image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of YZlat

ASKER

Thank you!