MrS1ck
MrS1ck

Reputation: 237

Remove excess information from string in Powershell

Good morning. What I am trying to accomplish is easier said than done. With the code below, I return the following:

Group is owned by: @{samaccountname=aduser1}

Group is owned by: @{samaccountname=aduser2}

Here's the code:

$GroupList = get-content "Z:\text.txt"

ForEach($Entry in $GroupList){

$SubGroups = @()

$AllMembers = @()

$strGroupOwner = Get-ADGroup -identity $Entry -Properties ManagedBy | select managedby 

$strOwnerName = get-aduser -identity $strGroupOwner.managedby -properties samaccountname |select samaccountname

 "Group is owned by: " + $strOwnerName

I simply need to remove '@{samaccountname=' and the '}' at the end from my string $strOwnerName before passing it through to the next step to make my resume something closer to:

Group is owned by: aduser1

Group is owned by: aduser2

All I was able to find on Google was removing 'White Space'. Any help or reading material would be most appreciated.

Thanks!

Upvotes: 0

Views: 2187

Answers (2)

alroc
alroc

Reputation: 28174

Use the -expandproperty parameter for select-object.

$strOwnerName = get-aduser -identity $strGroupOwner.managedby -properties samaccountname |select-object -expandproperty samaccountname

Also note that I've used select-object instead of the alias select; aliases should be avoided in scripts because they make an assumption about the execution environment which may not always be true.

Upvotes: 1

Raf
Raf

Reputation: 10107

In your code $strOwnerName is a PSCustomObject. To convert it to a string change

$strOwnerName = get-aduser -identity $strGroupOwner.managedby -properties samaccountname |select samaccountname

to

$strOwnerName = get-aduser -identity $strGroupOwner.managedby -properties samaccountname |select -ExpandProperty samaccountname

or

$strOwnerName = (get-aduser -identity $strGroupOwner.managedby).samaccountname

Upvotes: 1

Related Questions