如何从输出-Powershell中删除大括号/卷曲括号

时间:2014-06-04 20:56:07

标签: powershell powershell-v2.0 powershell-v3.0

如何从输出中删除大括号/卷曲括号

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

姓名全名
---- --------
{Anon} {Anon Xen1}
{Anon1} {Anon1 Xen2}
{Anon2} {Anon2 Xen3}

2 个答案:

答案 0 :(得分:4)

首先有大括号的原因是因为Name和FullName属性是集合而不是字符串。具体来说,它们是System.DirectoryServices.PropertyValueCollection个对象。

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

剪切了额外的属性

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

然后你可以创建一个自定义对象,并为它分配类似于前一个答案的值,但是我会迭代整个集合而不是任意抓取第一个成员。

$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

如果您想将其缩短为一个班轮,您可以使用以下内容:

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

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

答案 1 :(得分:1)

这样的事情,也许是:

([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
}