0

All i'm using this code to get data from SharePoint List and export it to txt file as you see i'm using New-Object PSObject to get this

my question is how can i sort the the properties by the name i gave or how to export this items sorted by those name Thanks in advance

$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 Answers1

0

If you know the propertynames, then use the following:

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

If you don't know the name of the properties, try:

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

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

I made a few other modifications to your script to make it more efficient and easier to read:

$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
Frode F.
  • 52,376
  • 9
  • 98
  • 114