{"id":65073,"date":"2007-04-16T21:12:00","date_gmt":"2007-04-16T21:12:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/04\/16\/how-can-i-read-the-contents-of-a-text-file-and-then-declare-the-contents-as-variables\/"},"modified":"2007-04-16T21:12:00","modified_gmt":"2007-04-16T21:12:00","slug":"how-can-i-read-the-contents-of-a-text-file-and-then-declare-the-contents-as-variables","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-read-the-contents-of-a-text-file-and-then-declare-the-contents-as-variables\/","title":{"rendered":"How Can I Read the Contents of a Text File and Then Declare the Contents as Variables?"},"content":{"rendered":"<p><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" height=\"34\" alt=\"Hey, Scripting Guy! Question\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"> \n<P>Hey, Scripting Guy! How can I read the contents of a text file, and then declare those contents as variables?<BR><BR>&#8212; TC<\/P><IMG height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" height=\"34\" alt=\"Hey, Scripting Guy! Answer\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" height=\"288\" alt=\"Script Center\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" align=\"right\" border=\"0\"><\/A> \n<P>Hey, TC. Before we begin, did you <I>really<\/I> ask us this question? We\u2019re positive that you did, but, the way things have been going lately, we can\u2019t be too sure.<\/P>\n<P>For example, by now everyone has heard that Scripting Guy Jean Ross went down to San Diego for the MMS conference, only to return with nearly a dozen surgical <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/topics\/mms2007\/tuesday.mspx\"><B>staples in her head<\/B><\/A>.<\/P>\n<TABLE class=\"dataTable\" id=\"EHD\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD class=\"\">\n<P class=\"lastInCell\"><B>Note<\/B>. If you <I>haven\u2019t<\/I> heard, Jean was taking a leisurely stroll through the San Diego Zoo when she noticed that a group of kindergarteners, on a field trip, had accidentally wandered into the grizzly bears\u2019 compound. With complete and utter disregard for her own well-being Jean leaped over the fence, fought off the bears, and carried each and every child to safety. As it turned out, during the battle one of grizzlies took a swipe at Jean\u2019s head and managed to inflict a nasty gash. After the children were all safe and sound, Jean \u2013 true to form \u2013 went back into the compound, performed first aid on the grizzly\u2019s paw, and only then went to the hospital and had her own wound tended to.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>But here\u2019s the weird part (interestingly enough, for Jean getting her head stapled together <I>wasn\u2019t<\/I> the weird part). The other day our Scripting Hero called the insurance company with a question about her claim; the insurance company told her that they had no record of her being treated in San Diego. Apparently she <I>hadn\u2019t<\/I> had her head stapled back together while in San Diego!<\/P>\n<P>It gets weirder. <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/apr07\/hey0413.mspx\"><B>Last week<\/B><\/A> the Scripting Guy who writes this column was writing this column when his computer died. When he tried restarting it (and he tried many times) he always got the same message: Non-system or disk error. At one point he did manage to get into the BIOS, thinking he would run the hard disk diagnostic test. What happened? Nothing: that option was grayed-out. Apparently the computer didn\u2019t <I>have<\/I> a hard disk.<\/P>\n<P>At that point the Scripting Guy who writes this column did what Scripting Guys always do in times of crisis: he went to lunch. When he came back he decided to try the computer one more time, just for the heck of it. Needless to say, it booted up just fine. He restarted it again, and again. No problem. He got back into the BIOS and discovered that his computer did have a hard disk; on top of that, it passed all the diagnostic checks with flying colors. Apparently his computer hadn\u2019t died after all.<\/P>\n<P><I>Very<\/I> weird.<\/P>\n<P>So, anyway, we can\u2019t be sure, TC, that you actually asked a question about reading lines from a text file and then declaring that information as variables. However, if you <I>did<\/I> ask a question about reading lines from a text file and then declaring that information as variables here\u2019s the answer. <\/P>\n<P>Unless, of course, it turns out that we didn\u2019t answer your question after all. But let\u2019s try the following and see what happens:<\/P><PRE class=\"codeSample\">Const ForReading = 1<\/p>\n<p>Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForReading)<\/p>\n<p>Do Until objFile.AtEndOfStream\n    strLine = objFile.ReadLine\n    Execute strLine\nLoop<\/p>\n<p>objFile.Close<\/p>\n<p>Wscript.Echo strFirstName\nWscript.Echo strLastName\n<\/PRE>\n<P>OK. If we understand your question (that is, the question you either did or did not ask), you have a text file with lines similar to this:<\/P><PRE class=\"codeSample\">strFirstName = &#8220;Ken&#8221;\nstrLastName = &#8220;Myer&#8221;\n<\/PRE>\n<P>As you can see, each line looks an awful lot like a line of code assigning a value to a variable; in fact, if you typed these lines as-is into a script you\u2019d end up with a variable named strFirstName (with a value of <I>Ken<\/I>) and a variable named strLastName (with a value of <I>Myer<\/I>). Of course, you don\u2019t <I>want<\/I> to type those lines as-is into a script; instead, you want to read those lines from a text file and then execute each line as if you <I>had<\/I> typed it into the script. In other words, you want your script to function as though you had typed in those two lines of code, even though you never actually typed in those two lines of code.<\/P>\n<P>See? We <I>told<\/I> you everything was getting weird!<\/P>\n<P>So how are we going to do all that (whatever it is)? Well, we\u2019re going to start off by defining a constant named ForReading and setting the value to 1; that\u2019s a constant we\u2019ll need when we open the text file. After the constant has been defined we next create an instance of the <B>Scripting.FileSystemObject<\/B> object and then open the file C:\\Scripts\\Test.txt:<\/P><PRE class=\"codeSample\">Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objFile = objFSO.OpenTextFile(&#8220;C:\\Scripts\\Test.txt&#8221;, ForReading)\n<\/PRE>\n<P>Now for the good part. What we need to do next is read in the text file line-by-line, and then execute each line in the text file as though it was a line of code we had typed into our script. (Why do we keep using the verb \u201cexecute?\u201d You\u2019ll find out in just a second.) To do that, we first set up a Do Until loop designed to run until we reach the end of the text file (that is, until the file\u2019s <B>AtEndOfStream<\/B> property is True). Inside that loop we use the <B>ReadLine<\/B> method to read the first line from the text file and then store that value in a variable named strLine:<\/P><PRE class=\"codeSample\">strLine = objFile.Readline\n<\/PRE>\n<P>Got that? That simply means that strLine is equal to this:<\/P><PRE class=\"codeSample\">strFirstName = &#8220;Ken&#8221;\n<\/PRE>\n<P>Is that going to help us? You bet it is. To create a variable named strFirstName, with a value of <I>Ken<\/I>, all we have to do now is call the <B>Execute<\/B> statement followed by the value to be executed:<\/P><PRE class=\"codeSample\">Execute strLine\n<\/PRE>\n<P>The Execute statement is a little-known yet interesting feature of VBScript; among other things, this statement enables you to execute a string value (or variable) as if you had typed that value into your script as a line of code. Confusing? Yes. But take a look at this sample script:<\/P><PRE class=\"codeSample\">strMessage = &#8220;Hi&#8221;\nstrCode = &#8220;Msgbox strMessage&#8221;\nExecute strCode\n<\/PRE>\n<P>Here we\u2019ve stored the text value <I>Hi<\/I> into a variable named strMessage. We\u2019ve then assigned the following value to a variable named strCode:<\/P><PRE class=\"codeSample\">Msgbox strMessage\n<\/PRE>\n<P>And you\u2019re right, that <I>does<\/I> look like a line of code for displaying the value of strMessage in a message box. And there\u2019s a good reason for that: it <I>is<\/I> a line of code for displaying the value of strMessage in a message box. That\u2019s the whole idea. In order to now run that line of code (that is, in order to display the message box) all we have to do is call the Execute statement followed by the string value (in this case, the variable strCode) we want to execute.<\/P>\n<P>Give it a try and you\u2019ll see what we\u2019re talking about.<\/P>\n<P>At any rate, when we call the Execute statement we end up executing this value:<\/P><PRE class=\"codeSample\">strFirstName = &#8220;Ken&#8221;\n<\/PRE>\n<P>And guess what? That\u2019s going to create a variable named strFirstName and assign it the value <I>Ken<\/I>. And then we\u2019re going to loop around and repeat this process with the next line in the text file.<\/P>\n<P>Admittedly, this all sounds crazy. But look at what we get back when we echo back the values of strFirstName and strLastName:<\/P><PRE class=\"codeSample\">Ken\nMyer\n<\/PRE>\n<P>Obviously strFirstName and strLastName are valid variables. And how do you suppose they got assigned their respective values? You got it: from the information found in the text file. Pretty cool, huh?<\/P>\n<P>Admittedly, we\u2019re not sure how often you\u2019ll need to read lines of code from a text file and then declare those lines of code as variables. Nevertheless, there are times when the Execute statement is invaluable. What times? Well, for at least one example, see <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/funzone\/games\/solutions07\/avbsol09.mspx\"><B>this event<\/B><\/A> from the 2007 Winter Scripting Games.<\/P>\n<P>Anyway, we hope that answers your question, TC. If it turns out that you didn\u2019t actually <I>ask<\/I> us a question, well, that\u2019s OK: the ways things have been going lately we\u2019re not so sure we answered the question anyway. Have we mentioned the two Scripting Guys who signed up for <A href=\"http:\/\/www.microsoft.com\/events\/teched2007\/default.mspx\" target=\"_blank\"><B>TechEd 2007<\/B><\/A> and received emails confirming their registration, then a few days later received emails telling them that they <I>hadn\u2019t <\/I>registered? Only then to be told that they <I>did<\/I> register after all. Only \u2013 well, never mind. Most likely none of that happened, either. Either way, we\u2019ll see everyone at TechEd 2007.<\/P>\n<P>Assuming, of course, that there <I>is<\/I> such a thing as TechEd 2007.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I read the contents of a text file, and then declare those contents as variables?&#8212; TC Hey, TC. Before we begin, did you really ask us this question? We\u2019re positive that you did, but, the way things have been going lately, we can\u2019t be too sure. For example, by now [&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-65073","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 read the contents of a text file, and then declare those contents as variables?&#8212; TC Hey, TC. Before we begin, did you really ask us this question? We\u2019re positive that you did, but, the way things have been going lately, we can\u2019t be too sure. For example, by now [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65073","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=65073"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65073\/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=65073"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=65073"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=65073"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}