Skeer
Skeer

Reputation: 173

Displaying just a piece of a variable?

$string = "@{Samaccountname=Fname.Lname}

What's the easiest way to remove "@{Samaccountname=" and the trailing "}" so only the fname.lname are returned?

I've tried $string.trim("@{Samaccountname=","}") and $string -replace {"@{Samaccountname=",""}

Even tried $string.trim("@","{","}") but I assume there is a better way than quaoting each character individually.

Neither of which worked.. I totally suck at regex so I haven't ventured down that path.

Upvotes: 0

Views: 81

Answers (2)

AdminOfThings
AdminOfThings

Reputation: 25031

An output of syntax @{propery = value} is likely a custom object converted to a string. It would be wise to work with the original object, retrieve the target values, and manipulate the retrieved data as required. So if the intention is only to output a property value, then use Select-Object -Expand Property or member access $object.Property. Otherwise, objects that are not value types will contain properties and their conversion to string will be based on their ToString() override method.

$users = Get-AdUser -Filter "SamAccountName -like '*doe'"
$PropAndValue = $users | Select-Object SamAccountName # the objects' SamAccountName property and their values
$ValueOnly = $users | Select-Object -Expand SamAccountName # returns the objects' SamAccountName values only

"objects with property and value"
$PropAndValue
"`r`nstringified prop and value of first object`r`n"
[string]$PropAndValue[0]
"`r`nproperty values only`r`n"
$ValueOnly
"`r`nstringified first property value`r`n"
[string]$ValueOnly[0]

Output:

objects with property and value

SamAccountName
--------------
jane.doe
john.doe

stringified prop and value of first object

@{SamAccountName=jane.doe}

property values only

jane.doe
john.doe

stringified first property value

jane.doe

Upvotes: 1

alexzelaya
alexzelaya

Reputation: 255

This should work: $string.Replace("@{Samaccountname=","").Replace("}","")

Upvotes: 0

Related Questions