Hey, Scripting Guy! How Tin can I Use Windows PowerShell to Make up one's mind the Number of Lines in a Text File?

Hey, Scripting Guy! Question

Hey, Scripting Guy! I'yard using Windows PowerShell to determine the record count (i.e., the number of lines) in a text file I but created. If the file has 2 lines, no problem; my script reports back a value of 2. If the file only has ane line, however, I get back what looks to be the number of characters in the file. In other words, when I run the script I might get back 41, but I accept no idea what that 41 is: 41 records or 41 characters. I doubtable free radicals, sunspots, or a feature I don't know well-nigh. What am I missing here?
— RS

Spacer Hey, Scripting Guy! Answer Script Center

Hey, RS. Needless to say, this is an interesting problem, and you have some interesting theories as to why this problem even exists in the first identify. We have to admit that we were intrigued by the notion that free radicals (atomic molecules with unpaired electrons) might be responsible for PowerShell sometimes reporting back the number of lines in a file and sometimes reporting back the number of characters in a file; initially, that seemed like the respond.

However, it and so occurred to u.s.a. that the formation of radicals may involve the breaking of covalent bonds homolytically, a process that – as nosotros all know – requires meaning amounts of energy. On summit of that, no ane can contend with the fact that bond cleavage most often happens between ii atoms of similar electronegativity. To the best of our noesis PowerShell has been carefully constructed to ensure that all the atoms accept dissimilar electronegativity, making free radicals a less-likely culprit.

Note. Not that costless radicals are entirely off the hook, mind you. According to one theory, free radicals in the human body are responsible for many diseases, mayhap even for the aging process itself. According to this theory, the unpaired electron in a free radical essentially kidnaps an electron from another molecule, thus turning that molecule into a gratis radical. This new costless radical then goes off in search of a new electron, starting a chain reaction that eventually leads to "biological breakdown."

To tell yous the truth, the Scripting Guy who writes this cavalcade has no idea if that's how the aging process really works. (If yous demand detailed, showtime-hand information nigh aging and growing onetime, y'all need to talk to the Scripting Editor.) Nevertheless, he does programme to use this theory, and to cite free radicals, in his year-end performance review, specially when he gets to the question "Why did you fail to meet your commitments this past yr?"

Incidentally, if any of y'all are brusk an electron or two, well, simply let u.s. know. The Scripts Guys e'er have some spare electrons lying around the office; heck, Scripting Guy Peter Costantini has several boxes of electrons that have never fifty-fifty been opened!

OK, so much for gratuitous radicals. Sunspots are something nosotros can't then easily dismiss, withal. That's mainly because we live in the Seattle surface area and, considering of that, haven't seen the sun in years. Nonetheless, while sunspots accept been known to crusade interference with radio signals, there's non a lot of bear witness to suggest that sunspots are responsible for issues in determining how many lines are in a text file. We can't rule it out, but it seems a little far-fetched to usa.

Of course, the Scripting Guy who writes this column is still planning to blame sunspot action for his inability to run across his commitments over the past year.

Sadly, that is the best excuse he has.

That leaves us with RS' final thought: that this unusual beliefs is feature of Windows PowerShell. Could this foreign activity really be something that'south built into PowerShell? Let's see if nosotros can figure that out.

To begin with, suppose nosotros accept a text file consisting of the following 6 lines:

This is line 1. This is line 2. This is line 3. This is line 4. This is line 5. This is line half-dozen.        

Let'due south use a script like to RS' to retrieve the contents of this file, store that data in a variable named $a, and so report back the Length of the variable:

$a = Get-Content C:\Scripts\Test.txt $a.Length        

What practice we get dorsum when we run this script? We get back the following:

6        

Then far so proficient, eh?

Now permit'southward remove the last 5 lines from the text file, leaving us with this:

This is line one.        

What do we get back when we run the script confronting a one-line text file? We become back this:

15        

Eep. It looks like RS was right: when dealing with a 1-line text file, PowerShell counts the number of characters in the file rather than the number of lines in the file. And that's non expert, non good at all.

So is this considering of free radicals? Well, maybe. But earlier we start making wild accusations, let's run this script instead, and let'due south run information technology against our six-line text file:

$a = Get-Content C:\Scripts\Test.txt $a.GetType()        

What we're doing here is using the Go-Content cmdlet to recollect the contents of the file C:\Scripts\Test.txt, just like we did before. However, instead of echoing dorsum the Length of the variable $a, we're using the GetType method to gain some insight into the kind of object we're dealing with:

IsPublic IsSerial Name                                     BaseType -------- -------- ----                                     -------- Truthful     Truthful     Object[]                                 System.Array        

As you can see, we're working with an assortment here, with each line in the text file representing a single item in that assortment. That's why the Length property returns 6; with an array, the Length indicates the number of items in that array.

At present allow's run this script against a one-line text file. Here's what we get dorsum when we do that:

IsPublic IsSerial Name                                     BaseType -------- -------- ----                                     -------- True     True     String                                   Organisation.Object        

Well what do you know? In this case we're dealing with a string rather than an array. That's why we get back a 15 when nosotros inquire for the Length; with a cord value the Length is the number of characters in that string. When using the Get-Content cmdlet, it appears that a multi-line text file is returned as an array, while a single-line text file is returned equally a string. That explains why the Length property sometimes represents the number of lines in the file, and sometimes represents the number of characters in the file: sometimes we're dealing with an array, and sometimes nosotros're dealing with a string.

Admittedly, that's pretty darn exciting, except for one thing: how does it help RS with his problem? To exist honest, information technology doesn't. Simply this should:

$a = (Get-Content C:\Scripts\Examination.txt | Measure-Object) $a.Count        

Then what are we doing here? Well, once again we're using Get-Content to call back the contents of the file Test.txt. However, this time around nosotros pipe that information to the Measure-Object cmdlet and enquire Measure out-Object to make up one's mind the number of lines in the file for us. After nosotros've done that, we and then echo back the value of the Count belongings. When we run this revised script against our half dozen-line text file nosotros go back the following:

6        

And when we run this script confronting our one-line text file? We get back this:

i        

Hallelujah! All we have to do is turn this problem over to Measure-Object and we're habitation free.

Incidentally, this works considering – by default – Measure out-Object uses the line count as the default measure when working with a text file. However, we can be more specific – and get back boosted information about a text file – just past adding the –line, -discussion, and/or the –character parameter. For example, suppose we run this command against our six-line text file:

$a = (Get-Content C:\Scripts\Exam.txt | Measure out-Object -line -discussion -character)        

Here's what we'll get back:

          Lines                         Words                    Characters Property                         -----                         -----                    ---------- --------                             six                            24                            xc        

Pretty absurd, huh?

That should do information technology, RS; if you have any questions please allow united states of america know. Only please let us know before December 21, 2012; later on all, co-ordinate to some interpretations of the Mayan Agenda, that's the day that the world is going to end. And why is the world supposed to cease on that solar day? You lot got it: this fourth dimension it is because of sunspots. According to some people, a burst of intense sunspot activity volition "…flip the sun'due south magnetic field, causing earthquakes and flooding on earth … and alter[ing] the endocrine production of the pineal gland."

And yes, as a thing of fact those are the very aforementioned things the Scripting Guy who writes this column was blamed for on his last performance review. In his defense, however, it'south not like he meant to flip the sunday's magnetic field; sometimes these things just happen.