2

I am trying to use powershell to export rest API to CSV with the following code

$DesiredProperties | Export-CSV -Path ".\Testrestapi.csv" -Encoding ASCII -NoTypeInformation

It outputs the following to CSV:

,
"105283","TickerID"
"2365512290","TickerID"
,
,
,
,
"US594918AH79","ISIN"
,
,
,
,
"US594918AH79","ISIN"
"2121687888","TickerID"
"US594918AH79","ISIN"
,

Desired result:

"105283","TickerID"
"2365512290","TickerID"
"US594918AH79","ISIN"
"US594918AH79","ISIN"
"2121687888","TickerID"
"US594918AH79","ISIN"

I tried using

(gc file.txt) | ? {$_.Trim() -ne ""} | Set-Content file.txt

but it seems it is not working for CSV files. Could someone please show me which command I should be using in this script to remove empty lines ", , , ,"

3
  • What is $DesiredProperties ? Is it content from a file ? Commented Apr 29, 2019 at 8:18
  • ? {$_.Trim() -ne ""} -> ? {$_.Trim(',')} Commented Apr 29, 2019 at 8:19
  • Yes. In this case tickercode, ticker_code_type Commented Apr 29, 2019 at 8:19

1 Answer 1

3

You could use Where-Object { $_.PSObject.Properties.Value -ne '' } to clean up the $DesiredProperties object directly.

Example:

Input data: "C:\Temp\Testrestapi.csv" (I use your CSV here, but you should take your export object from the REST API directly:

,
"105283","TickerID"
"2365512290","TickerID"
,
,
,
,
"US594918AH79","ISIN"
,
,
,
,
"US594918AH79","ISIN"
"2121687888","TickerID"
"US594918AH79","ISIN"
,

Sample code:

Import-Csv -Path "C:\Temp\Testrestapi.csv" -Header 'col1','col2' | Where-Object { $_.PSObject.Properties.Value -ne '' } | Export-Csv -Path "C:\Temp\Testrestapi_clean.csv" -NoTypeInformation

Output data: "C:\Temp\Testrestapi_clean.csv":

"col1","col2"
"105283","TickerID"
"2365512290","TickerID"
"US594918AH79","ISIN"
"US594918AH79","ISIN"
"2121687888","TickerID"
"US594918AH79","ISIN"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.