header image

Get-Content and Numbers

Posted by: | March 1, 2017 Comments Off on Get-Content and Numbers |

A common technique is to put a list of information into a text file and read that using Get-Content. The information is often server names. This works great when the data is strings but breaks down if you’re dealing with numbers.

Lets start with a text file containing some numbers:

PS> Get-Content -Path .\num.txt
1000
109
258
331
699
744
829

Let’s try and sort those numbers:

PS> Get-Content -Path .\num.txt | sort
1000
109
258
331
699
744
829

It may seem that nothing is happening but if you sort descending:

PS> Get-Content -Path .\num.txt | sort -Descending
829
744
699
331
258
109
1000

Things change but not quite in the way that you might think. The data isn’t being sorted numerically its being sorted as strings.

PS> Get-Content -Path .\num.txt | Get-Member
TypeName: System.String

If you read the help file for Get-Content it states that the cmdlet returns either strings or bytes depending on the content of the file.

So if Get-Content returns strings what can we do if we want to work with the file contents as numbers rather than text.

You have a few choices. You can force a type conversion (known in programming circles as a cast) in a number of ways.

First using the –as operator

PS> Get-Content -Path .\num.txt | foreach {$psitem -as [int]} | sort
109
258
331
699
744
829
1000

That’s more like a numeric sort

You can cut down on the code:

PS> Get-Content -Path .\num.txt | foreach {[int]$psitem} | sort
109
258
331
699
744
829
1000

Or you can use foreach to call  a method on the object

PS> Get-Content -Path .\num.txt | foreach ToInt32($psitem) | sort
109
258
331
699
744
829
1000

You can even use the foreach method on the array that Get-Content creates

PS> (Get-Content -Path .\num.txt).foreach({[int]$psitem})  | sort
109
258
331
699
744
829
1000

The last option is the fastest but is only available on PowerShell 4.0 and above.

Get-Content returns strings but its not difficult to turn them into the numbers you need

under: PowerShell Basics

Comments are closed.

Categories