2

I am trying to import a CSV file and then sort by a colum. Cant seem to make it work.

$csvPath = 'path/to/usage_new.csv'
$usage = Get-Content -Path $csvPath | Select-Object -Skip 2 | Sort-Object "Percentage Used" | Out-String | ConvertFrom-Csv
foreach ($usage1 in $usage) {Write-Host Number $usage1.Phone used $usage1."Percentage Used"%}

This is just pretty basic but the Sort-Object does not work?

It imports and prints to screen OK

Any advice would be great!

Thanks

1 Answer 1

4

Get-Content reads lines of text into strings, strings don't have properties called "Percentage Used", they only have a Length.

You need to convert from CSV before you do the sorting, so the incoming data has "Percentage Used" properties built from the column title:

Import-Csv -Path $csvPath | 
    Select-Object -Skip 2 |
    Sort-Object -Property 'Percentage Used' |
    Select-Object Phone, @{Name='Used'; Expression={"{0}%" -f $_.'Percentage Used'}}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! That works but only if I take out the 'Select-Object -Skip 2' and remove the top two 'blank' lines from the CSV file?
That makes sense; Import-Csv is expecting quite a strict format of input, the top line becomes the headers and if it's blank, no headers to read...
OK thanks. I cant quite figure how to output the text now using my 'foreach' statement - but I can play around with that unless you have some advice!
Well, I advise you not to :p That's why I put the last Select-Object in, to try and show the output in a neat PowerShell style table. Unless it really needs to be as a string, then take the last line off and replace it with ForEach-Object { 'Number {0} used {1}%' -f $_.Phone, $_.'Percentage Used' } - it's not a great habit to get into using Write-Host for general output in PS unless you know you need it.

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.