{"id":63653,"date":"2007-11-06T00:22:00","date_gmt":"2007-11-06T00:22:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/11\/06\/hey-scripting-guy-how-can-i-make-the-name-of-the-file-the-first-line-of-each-text-file-in-a-folder\/"},"modified":"2007-11-06T00:22:00","modified_gmt":"2007-11-06T00:22:00","slug":"hey-scripting-guy-how-can-i-make-the-name-of-the-file-the-first-line-of-each-text-file-in-a-folder","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-make-the-name-of-the-file-the-first-line-of-each-text-file-in-a-folder\/","title":{"rendered":"Hey, Scripting Guy! How Can I Make the Name of the File the First Line of Each Text File in a Folder?"},"content":{"rendered":"<p><H2><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\"> <\/H2>\n<P>Hey, Scripting Guy! How can I make the name of the file the first line of each and every text file in a folder?<BR><BR>&#8212; DJ<\/P><IMG border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" border=\"0\" alt=\"Script Center\" align=\"right\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" height=\"288\"><\/A> \n<P>Hey, DJ. And, by the way, we hope your day is going better than ours. Are we having a bad day? You might say that. For example, this morning the Scripting Guy who writes this column zoomed right past the grocery store where he buys doughnuts every day. <I>A Scripting Guy forgetting about doughnuts<\/I>?!? If that\u2019s not a bad omen, well, we don\u2019t know what is.<\/P>\n<TABLE id=\"E6C\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P class=\"lastInCell\"><B>Note<\/B>. Don\u2019t worry: he turned around, went back to the store, and got his doughnuts after all. Sure, that made him a little late for work. But priorities are priorities, right?<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>Believe it or not, things seemed to get progressively worse as the day went on. As it was, the only thing keeping him going was the fact that this column was written on Friday. That meant that \u2013 as the Scripting Guy wrote this column \u2013 the next day was a Saturday. And Saturday\u2019s are <I>always<\/I> good days.<\/P>\n<P>Well, except when the Washington Huskies (who have given up 170 points in their past four games alone) have a football game, that is. Which they do. <\/P>\n<P>Oh, well, maybe Sunday will be a better day. After all the forecast for Sunday calls for \u2013 you know what? Never mind. We\u2019ll just sit here and feel sorry for ourselves.<\/P>\n<P>Hmmm \u2026. Turns out that sitting around and feeling sorry for yourself isn\u2019t as much fun as we thought it would be. (So many people do that here at Microsoft that we assumed it must be fun.) OK, then, let\u2019s see if there\u2019s something else we can do to kill a little time. Tell you what, why don\u2019t we see if we can figure out an answer to today\u2019s question.<\/P>\n<P>And, sure, what the heck: we\u2019ll even see if we can figure out a <I>correct<\/I> answer to today\u2019s question.<\/P>\n<P>Before we do that, let\u2019s briefly explain the setting for today\u2019s column. According to DJ\u2019s email, he has a series of text files containing temperature data. Those text files look something like this:<\/P><PRE class=\"codeSample\">45.544 34.544 65.433 56.783\n32.451 65.432 22.435. 44.564\n<\/PRE>\n<P>What DJ would <I>like<\/I> is to have a script that could run through all the files in that folder and, for each one, insert the file name as the first line in the text file; that way these files can be imported into another software program. (<I>What<\/I> software program? Oh, no you don\u2019t; we still haven\u2019t forgotten what happened <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/oct07\/hey1019.mspx\"><B>the last time<\/B><\/A> we mentioned a third-party software program.) In other words, DJ would like to end up with a series of text files that look something like this:<\/P><PRE class=\"codeSample\">apr_avg_temp\n45.544 34.544 65.433 56.783\n32.451 65.432 22.435. 44.564\n<\/PRE>\n<P>But you know what the Rolling Stones said, don\u2019t you, DJ? You can\u2019t always get what you want.<\/P>\n<P>Fortunately, though, in this case you <I>can<\/I> get what you want. Here\u2019s a script that can make the file name the first line in the text file, and do that for every file in a folder:<\/P><PRE class=\"codeSample\">Const ForReading = 1\nConst ForWriting = 2<\/p>\n<p>Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)<\/p>\n<p>strComputer = &#8220;.&#8221;<\/p>\n<p>Set objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set colFiles = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\TemperatureData&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)<\/p>\n<p>For Each objFile in colFiles\n    strFileName = objFile.FileName\n    strFilePath = objFile.Name<\/p>\n<p>    Set objFile = objFSo.OpenTextFile(strFilePath, ForReading)\n    strContents = objFile.ReadAll\n    objFile.Close<\/p>\n<p>    Set objFile = objFSo.OpenTextFile(strFilePath, ForWriting)\n    strContents = strFileName &amp; vbCrLf &amp; strContents\n    objFile.Write strContents\n    objFile.Close\nNext\n<\/PRE>\n<TABLE id=\"EPE\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P class=\"lastInCell\"><B>Note<\/B>. Did that cheer us up any? Well, sure. But, then again, who <I>wouldn\u2019t<\/I> be cheered up at least a little by a script that uses both WMI <I>and<\/I> the FileSystemObject?<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>How does this script work? We\u2019ll tell you how. The script starts out by defining a pair of constants, ForReading and ForWriting; we\u2019ll need to use these two constants when we read from and write to each text file. After defining the two constants we then create an instance of the <B>Scripting.FileSystemObject<\/B>, the object that actually enables us to read from and write to text files.<\/P>\n<P>Our next task is to connect to the WMI service on the local computer. Now, usually when we write about WMI our next sentence is something along the lines of this:<\/P>\n<P>\u201cOf course, you can also run this script against a remote computer.\u201d <\/P>\n<P>That\u2019s not going to be our next sentence this time, however. Instead, <I>this<\/I> is going to be our next sentence:<\/P>\n<P>\u201cAnd before you ask, no, you can\u2019t run this script against a remote computer, at least not without making major changes to the code.\u201d<\/P>\n<P>So why <I>can\u2019t<\/I> we run this script against a remote computer? Can\u2019t WMI retrieve a collection of files from a remote machine?<\/P>\n<P>Well, yes, WMI <I>can<\/I> retrieve a collection of files from a remote machine. However, in this case WMI isn\u2019t the culprit; instead, the problem lies with the FileSystemObject, an object designed to work only with local files on the local computer. That doesn\u2019t mean that it\u2019s <I>impossible<\/I> to perform this task on a remote computer; however, like we said, to do so would involve making major changes to the code. If there\u2019s enough interest in running this script against remote machines, well, we\u2019ll see what we can do about that. In the meantime, you might want to <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/oct05\/hey1021.mspx\"><B>take a look at this<\/B><\/A><I>Hey, Scripting Guy!<\/I> column, which talks about working with text files on a remote machines.<\/P>\n<P>After we connect to the WMI service we use this line of code (and one of those awkward-looking Associators Of queries) to return a collection of all the files found in the folder C:\\TemperatureData:<\/P><PRE class=\"codeSample\">Set colFiles = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\TemperatureData&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)\n<\/PRE>\n<P>And now, at long last, we\u2019re ready to do some <I>real<\/I> work.<\/P>\n<TABLE id=\"EJG\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P class=\"lastInCell\"><B>Note<\/B>. OK, the <I>script<\/I> is ready to do some real work. That\u2019s not necessarily true of the Scripting Guys. Or at least not one of the Scripting Guys. <\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>At this point, the first thing we need to do is set up a For Each loop to loop through the collection of files found in C:\\TemperatureData. And what do we do inside that loop? For starters, this:<\/P><PRE class=\"codeSample\">strFileName = objFile.FileName\nstrFilePath = objFile.Name\n<\/PRE>\n<P>In the first line we\u2019re assigning the value of the <B>FileName<\/B> property to a variable named strFileName. In WMI, the FileName property is simply the name of the file, not including the file extension. For example, suppose we have the file C:\\TemperatureData\\Apr_avg_temp.txt. The value of the FileName property for this file? Apr_avg_temp.<\/P>\n<P>In line 2, we assign the value of the <B>Name<\/B> property to a variable named strFilePath. The name of this property (Name) is actually a bit misleading; in WMI, the file\u2019s Name is equivalent to the file <I>path<\/I>. That means that the file C:\\TemperatureData\\Apr_avg_temp.txt has a Name equal to, well, C:\\TemperatureData\\Apr_avg_temp.txt.<\/P>\n<P>As soon as we\u2019ve assigned values to our two variables we call the <B>OpenTextFile<\/B> method to open the first file in the collection; that\u2019s what we do with this line of code:<\/P><PRE class=\"codeSample\">Set objFile = objFSo.OpenTextFile(strFilePath, ForReading)\n<\/PRE>\n<P>After the file is open we use the <B>ReadAll<\/B> method to read in the entire contents of the file and store those contents in a variable cleverly-named strContents. (Why do we read the entire contents of the file into a variable? We\u2019ll explain that in a moment.) We then call the <B>Close<\/B> method to close the file.<\/P>\n<P>Yet another good question: why <I>do<\/I> we close the file? After all, don\u2019t we still need to make the file name the first line in the file? <\/P>\n<P>Well, yes, we do still need to do that. However, we initially opened our file for reading, something we had to do in order to read from the file. With the FileSystemObject you can open a file for reading or for writing, but you can\u2019t open a file for reading <I>and<\/I> for writing; instead, we have to open the file for reading, read from it, and then close the file. After that, we can then reopen the file, this time for writing.<\/P>\n<P>Which, coincidentally enough, is what we do with the very next line of code:<\/P><PRE class=\"codeSample\">Set objFile = objFSo.OpenTextFile(strFilePath, ForWriting)\n<\/PRE>\n<P>All that brings us to this line of code:<\/P><PRE class=\"codeSample\">strContents = strFileName &amp; vbCrLf &amp; strContents\n<\/PRE>\n<P>As we\u2019ve seen, the FileSystemObject is a bit temperamental. For one thing, it won\u2019t let you open a file for reading and writing; on top of that, it won\u2019t let you selectively modify a file, either. Instead, the only way to make changes to a file is to read the contents into memory, make the changes in memory, and then rewrite the entire file. That, by the way, explains why we read the entire contents of the file into memory: we have to make all our changes in memory.<\/P>\n<P>That also explains the line of code we just showed you; in that line we\u2019re constructing our new file contents by combining:<\/P>\n<TABLE border=\"0\" cellSpacing=\"0\" cellPadding=\"0\">\n<TBODY>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>The name of the file (stored in the variable strFileName).<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>A carriage return-linefeed (represented by the VBScript constant vbCrLf).<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P>The existing contents of the file (stored in the variable strContents).<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<P>Glommed together, that makes strContents equal to this:<\/P><PRE class=\"codeSample\">apr_avg_temp\n45.544 34.544 65.433 56.783\n32.451 65.432 22.435. 44.564\n<\/PRE>\n<P>Which, now that you mention it, is <I>exactly<\/I> what we want this file to look like, isn\u2019t it? And that\u2019s good, because that means that all we have to do now is call the <B>Write<\/B> method to replace the existing contents of the first file with the newly-modified contents currently in memory:<\/P><PRE class=\"codeSample\">objFile.Write strContents\n<\/PRE>\n<P>And then we simply close the file, return to the top of the loop, and repeat the process with the next file in the collection.<\/P>\n<P>That should do it, DJ. As for the Scripting Guy who writes this column, well, don\u2019t feel too bad for him; things are bound to start looking up sooner or later. Why, if nothing else, on Thursday morning the Scripting Guys head for Barcelona and the <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/topics\/teched07\/itpreview.mspx\"><B>TechEd IT Forum<\/B><\/A>. Let\u2019s see, dealing with the security lines at the airport; eating airline food; taking a 4 \u00bd hour flight to Atlanta; sitting around the Atlanta airport for 3 hours; taking a 9-hour flight across the Atlantic \u2013 you know what, that <I>will<\/I> be better than the day we had today, <I>way<\/I> better. See you all tomorrow.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I make the name of the file the first line of each and every text file in a folder?&#8212; DJ Hey, DJ. And, by the way, we hope your day is going better than ours. Are we having a bad day? You might say that. For example, this morning the [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[3,4,14,5],"class_list":["post-63653","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-scripting-guy","tag-scripting-techniques","tag-text-files","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! How can I make the name of the file the first line of each and every text file in a folder?&#8212; DJ Hey, DJ. And, by the way, we hope your day is going better than ours. Are we having a bad day? You might say that. For example, this morning the [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/63653","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=63653"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/63653\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=63653"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=63653"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=63653"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}