How to remove Braces/Curly Brackets from output -Powershell

好久不见. 提交于 2019-12-11 12:58:38

问题


How to remove Braces/Curly Brackets from output

$t = [ADSI]"WinNT://$env:COMPUTERNAME"
$t1 = $adsi.PSBase.Children |where {$_.SchemaClassName -eq 'user'}  
$t1 |select Name,Fullname

Name Fullname
---- --------
{Anon} {Anon Xen1}
{Anon1} {Anon1 Xen2}
{Anon2} {Anon2 Xen3}


回答1:


The reason there are curly braces in the first place is because the Name and FullName properties are collections not strings. Specifically they are System.DirectoryServices.PropertyValueCollection objects.

$t = [adsi]"WinNT://$env:COMPUTERNAME"
$t1 = $t.PSBase.Children |where {$_.SchemaClassName -eq 'user'}
$t1[0]|get-member

Extra properties snipped

TypeName: System.DirectoryServices.DirectoryEntry
Name                        MemberType Definition
----                        ---------- ----------
FullName                    Property   System.DirectoryServices.PropertyValueCollection FullName {get;set;}
Name                        Property   System.DirectoryServices.PropertyValueCollection Name {get;set;}

You could then create a custom object and assign the values to it similar to the previous answer but I would iterate through the collection instead of arbitrarily grabbing the first member.

$t = [adsi]"WinNT://$env:COMPUTERNAME"
$t1 = $t.PSBase.Children |where {$_.SchemaClassName -eq 'user'}
$t1 | ForEach-Object{
    $temp = New-Object PSObject -Property @{
        "Name" = $_.Name | ForEach-Object {$_}
        "FullName" = $_.FullName | ForEach-Object {$_}
    }
    $temp
}

Name                                                        FullName
----                                                        --------
Administrator
Guest

If you would like to shorten it to a one liner you can use the following:

([adsi]"WinNT://$env:COMPUTERNAME").PSBase.Children|?{$_.SchemaClassName -eq 'user'}|%{$temp=""|Select Name,FullName;$temp.Name=$_.Name|%{$_};$temp.FullName=$_.FullName|%{$_};$temp}

Name                                                        FullName
----                                                        --------
Administrator
Guest



回答2:


Something like this, perhaps:

([ADSI] "WinNT://$Env:COMPUTERNAME").PSBase.Children |
  where-object { $_.schemaClassName -eq "user" } | foreach-object {
  $name = & { if ( $_.Name ) { $_.Name[0] } else { $NULL } }
  $fullName = & { if ( $_.FullName ) { $_.FullName[0] } else { $NULL } }
  new-object PSObject -property @{
    "Name" = $name
    "FullName" = $fullName
  } | select-object Name,FullName
}


来源:https://stackoverflow.com/questions/24047408/how-to-remove-braces-curly-brackets-from-output-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!