排序对象Powershell的属性

时间:2014-05-18 06:06:20

标签: sorting powershell psobject

所有 我正在使用此代码从SharePoint列表中获取数据并将其导出到txt文件 如你所见,我正在使用New-Object PSObject来获取这个

我的问题是我如何按照我给出的名称对属性进行排序,或者如何导出按这些名称排序的项目 提前致谢

$MyWeb = Get-SPWeb "http://ilike-eg.suz.itcgr.net/SM"
$MyList = $MyWeb.Lists["SCGC"] 
$exportlist = @()
$Mylist.Items |  foreach {
$obj =   New-Object PSObject -property @{ 
        "A"="   "+$_["AACCOUNT_ID"]
        "B"="   "+$_["BTRANSACTION_ID"]
        "C"="          "+$_["CDATE"] 
        "D"="      "+$_["DCUSTOMER_ID"]
        "E"="     "+$_["ECUSTOMER_NAME"]
        "F"=" "+$_["FAMOUNT"]
        "G"=$_["GCLASS"] 
} 
$exportlist += $obj | Sort-Object -descending   
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
$NameOnly = "CDP" 
$exportlist | Export-Csv -Delimiter "`t"-path "$NameOnly.txt" 
}
$a, ${d:CDP.txt} = Get-Content .\CDP.txt
$a, ${d:CDP.txt} = Get-Content .\CDP.txt
(Get-Content D:\CDP.txt) | 
Foreach-Object {$_ -replace $([char]34), ""} | 
Set-Content D:\CDP.txt
(Get-Content D:\CDP.txt) | 
Foreach-Object {$_ -replace "/", "-"} | 
Set-Content D:\CDP.txt
(Get-Content D:\CDP.txt) | 
Foreach-Object {$_ -replace "`t", ""} | 
Set-Content D:\CDP.txt

1 个答案:

答案 0 :(得分:0)

如果您知道属性名称,请使用以下内容:

$exportlist |
Select-Object A,B,C,D,E,F,G |
Export-Csv -Delimiter "`t"-path "$NameOnly.txt"

如果您不知道属性的名称,请尝试:

$properties = $exportlist |
Foreach-Object { $_.psobject.Properties | Select-Object -ExpandProperty Name } |
Sort-Object -Unique

$exportlist |
Select-Object $properties |
Export-Csv -Delimiter "`t"-path "$NameOnly.txt"

我对您的脚本进行了一些其他修改,以使其更高效,更易于阅读:

$MyWeb = Get-SPWeb "http://ilike-eg.suz.itcgr.net/SM"
$MyList = $MyWeb.Lists["SCGC"] 
$exportlist = @()

$Mylist.Items |  ForEach-Object {
    $obj =   New-Object PSObject -property @{ 
            "A"="   "+$_["AACCOUNT_ID"]
            "B"="   "+$_["BTRANSACTION_ID"]
            "C"="          "+$_["CDATE"] 
            "D"="      "+$_["DCUSTOMER_ID"]
            "E"="     "+$_["ECUSTOMER_NAME"]
            "F"=" "+$_["FAMOUNT"]
            "G"=$_["GCLASS"] 
    }

    #Remove unnecessary sort
    $exportlist += $obj   
    $DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
    $NameOnly = "CDP" 

    #Exporting with sorted properties
    $exportlist |
    Select-Object A,B,C,D,E,F,G |
    Export-Csv -Delimiter "`t"-path "$NameOnly.txt"
}

#Removed duplicate get-content line
$a, ${d:CDP.txt} = Get-Content .\CDP.txt

#Combined replace statements to avoid multiple read/writes
(Get-Content D:\CDP.txt) |
Foreach-Object {$_ -replace $([char]34) -replace "`t" -replace '/', ''} |
Set-Content D:\CDP.txt