{"id":55363,"date":"2008-06-13T02:06:00","date_gmt":"2008-06-13T02:06:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2008\/06\/13\/hey-scripting-guy-how-can-i-run-a-command-line-tool-multiple-times-and-save-the-output-to-a-text-file\/"},"modified":"2008-06-13T02:06:00","modified_gmt":"2008-06-13T02:06:00","slug":"hey-scripting-guy-how-can-i-run-a-command-line-tool-multiple-times-and-save-the-output-to-a-text-file","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-run-a-command-line-tool-multiple-times-and-save-the-output-to-a-text-file\/","title":{"rendered":"Hey, Scripting Guy! How Can I Run a Command-Line Tool Multiple Times and Save the Output to a Text File?"},"content":{"rendered":"<p><img decoding=\"async\" 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\" \/> <\/p>\n<p>Hey, Scripting Guy! I\u2019m trying to write a script that will run Fsutil.exe against all the drives on a computer. That\u2019s pretty easy. However, I\u2019d like to have all the output written to a text file rather than displayed on screen; that\u2019s the part that I haven\u2019t had much luck with. Any help here would be greatly appreciated.<br \/>&#8212; RS<\/p>\n<p><img decoding=\"async\" border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\" \/><img decoding=\"async\" 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 decoding=\"async\" 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> <\/p>\n<p>Hey, RS. Well, the Scripting Guys are back from Orlando \u2013 barely. The Scripting Guys were <i>supposed<\/i> to arrive back in Seattle last night around 9:30 PM, an arrival time that \u2013 among other things \u2013 would have given the Scripting Guy who writes this column time to write this column. However, thanks to a thunderstorm that hovered directly over the airport, the Scripting Guys spent several hours sitting on the tarmac in Orlando, and didn\u2019t actually get home until 1:00 AM Seattle time. That\u2019s bad; even worse is the fact that, since the Scripting Guys were operating on Eastern Daylight Time, 1:00 AM Seattle time felt like 4:00 AM to them.<\/p>\n<p>And, of course, there was the little matter of sitting in a cramped little seat on an airplane for 8 hours, with a good portion of that devoted to sitting on the tarmac. As you might expect, the plane was parked right next to one of the gates, but no one was allowed to leave the plane. To help make up for this inconvenience, however, the airlines <i>did<\/i> give everyone a 1-ounce bag of \u201cSavory Snack Mix,\u201d for <i>free<\/i>!<\/p>\n<p>In the end, that means that today\u2019s <i>Hey, Scripting Guy!<\/i> column did not get written the night before as planned. As a matter of fact, a somewhat groggy Scripting Guy is pretty much writing today\u2019s column while you read it; we only hope we can get that last paragraph typed in before you reach the end of the article. <\/p>\n<table id=\"ELD\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td>\n<p><b>Note<\/b>. If you could go get a cup of coffee, go to the bathroom, or otherwise stop working for a few minutes that would help us out a great deal. Hey, there\u2019s an idea: maybe you <i>could<\/i> do some work for a few minutes.<\/p>\n<p>Nah; never mind about doing some work. After all, we\u2019d never make anyone do something that we wouldn\u2019t do ourselves.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>With all that in mind, maybe we should see what we can do about answering RS\u2019 question:<\/p>\n<pre class=\"codeSample\">Set objShell = CreateObject(\"WScript.Shell\")\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nstrComputer = \".\"\n\nSet objWMIService = GetObject(\"winmgmts:\\\\\" &amp; strComputer &amp; \"\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery _\n    (\"Select * From Win32_LogicalDisk Where DriveType = 3\")\n\nFor Each objItem in colItems\n    strDriveLetter = objItem.DeviceID \n    strCommand = \"fsutil dirty query \" &amp; strDriveLetter\n    \n    Set objExecObject = objShell.Exec(strCommand)\n    Do While Not objExecObject.StdOut.AtEndOfStream\n        strResults = objExecObject.StdOut.ReadAll()\n    Loop\n\n    strText = strText &amp; strResults\nNext\n\nSet objFile = objFSO.CreateTextFile(\"C:\\Scripts\\Test.txt\")\nobjFile.Write strText\nobjFile.Close<\/pre>\n<table id=\"E3D\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td>\n<p><b>Note:<\/b> If you run this script on Windows Vista, be sure to run as an administrator. (Right-click on Command Prompt and select Run As Administrator.) If you don\u2019t, your output from this script will look something like this:<\/p>\n<pre class=\"codeSample\">The FSUTIL utility requires that you have administrative privileges.\nThe FSUTIL utility requires that you have administrative privileges.\n<\/pre>\n<p>Probably not exactly what you were hoping for.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>As you can see, this isn\u2019t a particularly complicated script. (Which is good, because the Scripting Guy who writes this column isn\u2019t particularly awake at the moment.) We kick the script off by creating instances of two COM objects: <b>Wscript.Shell<\/b>, the object we\u2019ll use to actually run Fsutil.exe; and <b>Scripting.FileSystemObject<\/b>, the object we\u2019ll use to write the output generated by Fsutil to a text file. After creating these two objects we connect to the WMI service on the local computer, then use this line of code to retrieve a collection of all the hard disks installed on that computer:<\/p>\n<pre class=\"codeSample\">Set colItems = objWMIService.ExecQuery _\n    (\"Select * From Win32_LogicalDisk Where DriveType = 3\")\n<\/pre>\n<p>Two quick notes here. First, we noted that we connected to the WMI service on the local computer. Could we run this same script against a <i>remote<\/i> computer? Well, no, not in its current state; that\u2019s because we can\u2019t use the Windows Script Host <b>Exec<\/b> method to kick off Fsutil on a remote machine. We <i>could<\/i> use WMI to run Fsutil, but then we&#8217;d have difficulty capturing the output and writing it to a text file. If you need to run this script against a remote machine, you\u2019ll probably have to rely on Windows Script Host\u2019s remote capabilities. For more information on those capabilities, see the <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/guide\/sas_wsh_immo.mspx\"><b>Microsoft Windows 2000 Scripting Guide<\/b><\/a>.<\/p>\n<p>Second, you might note that, in our WQL query, we restricted the returned data to instances of the <b>Win32_LogicalDisk<\/b> class where the <b>DriveType<\/b> is equal to 3. As you might have guessed, anything that has a drive type equal to 3 is a hard disk (fixed disk).<\/p>\n<p>So what happens after we get back this collection of hard disks? Well, to begin with, we set up a For Each loop to walk us through each item in the collection:<\/p>\n<pre class=\"codeSample\">For Each objItem in colItems<\/pre>\n<p>Inside the loop, we grab the value of the <b>DeviceID<\/b> property (which just happens to be equivalent to the drive letter), and store that value in a variable named strDriveLetter. That brings us to this line of code:<\/p>\n<pre class=\"codeSample\">strCommand = \"fsutil dirty query \" &amp; strDriveLetter<\/pre>\n<p>What we\u2019re doing here is constructing the Fsutil command to run against the first hard disk on the computer. Assuming that the first drive on the computer is drive C, RS needs to run the following command:<\/p>\n<pre class=\"codeSample\">fsutil dirty query C:<\/pre>\n<p>By amazing coincidence, that\u2019s the exact same command we\u2019re constructing: we\u2019re combining the string value <b>fsutil dirty query<\/b> and the drive letter (DeviceID) C to form that exact command.<\/p>\n<p>Once we have this command we can use Windows Script Host\u2019s <b>Exec<\/b> method to execute the command:<\/p>\n<pre class=\"codeSample\">Set objExecObject = objShell.Exec(strCommand)<\/pre>\n<p>We use the Exec method here (as opposed to the Run method) for one reason and one reason only: the Exec method allows us to capture any output generated by Fsutil. In fact, that\u2019s what this block of code is for:<\/p>\n<pre class=\"codeSample\">Do While Not objExecObject.StdOut.AtEndOfStream\n    strResults = objExecObject.StdOut.ReadAll()\nLoop\n<\/pre>\n<p>All we\u2019re doing here is waiting patiently while Fsutil does its thing. Once the command-line tool has finished running, we use the <b>ReadAll<\/b> method to read in the output (from the StdOut stream) and store it in a variable named strResults.<\/p>\n<table id=\"EHG\" 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>. Incidentally, we can echo back the output as well as save it to a text file. If we also wanted to see the output onscreen we could simply add the line <b>Wscript.Echo strResults<\/b> immediately after the <b>Loop<\/b> statement.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>The moment we exit the Do While loop we then append the new set of data to a variable named strText:<\/p>\n<pre class=\"codeSample\">strText = strText &amp; strResults<\/pre>\n<p>From there we go back to the top of the loop and repeat the process with the next hard drive on the computer.<\/p>\n<p>After we\u2019ve run Fsutil against all the drives on the machine we use this block of code to write the complete results to a text file:<\/p>\n<pre class=\"codeSample\">Set objFile = objFSO.CreateTextFile(\"C:\\Scripts\\Test.txt\")\nobjFile.Write strText\nobjFile.Close\n<\/pre>\n<p>Needless to say, there\u2019s nothing very fancy going on here. In line 1 we\u2019re using the <b>CreateTextFile<\/b> method to create a new text file named C:\\Scripts\\Test.txt. In line 2, we use the <b>Write<\/b> method to write the value of the variable strText to this new file. Finally, in line 3 we close the text file and call it a day.<\/p>\n<p>By now we\u2019re more than just a little late with today\u2019s column, so we\u2019ll have to wait until tomorrow to fill you in on our trip to Orlando. We will mention, however, that the Scripting Guys got to ride the all-new <a href=\"http:\/\/www.universalorlando.com\/usf_attr_simpsons.html\" target=\"_blank\"><b>Simpsons ride<\/b><\/a> at Universal Studios. What was that like? Well, it was fun, but by the time we finished our stomachs were feeling a little queasy, and we definitely needed to sit down for awhile before we could even <i>think<\/i> about doing anything else.<\/p>\n<p>Which, now that you mention it, <i>does<\/i> sound a lot like what people experience when they read the <i>Hey, Scripting Guy!<\/i> column, doesn\u2019t it?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I\u2019m trying to write a script that will run Fsutil.exe against all the drives on a computer. That\u2019s pretty easy. However, I\u2019d like to have all the output written to a text file rather than displayed on screen; that\u2019s the part that I haven\u2019t had much luck with. Any help here would [&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":[2,3,4,5],"class_list":["post-55363","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-running","tag-scripting-guy","tag-scripting-techniques","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I\u2019m trying to write a script that will run Fsutil.exe against all the drives on a computer. That\u2019s pretty easy. However, I\u2019d like to have all the output written to a text file rather than displayed on screen; that\u2019s the part that I haven\u2019t had much luck with. Any help here would [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55363","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=55363"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55363\/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=55363"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=55363"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=55363"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}