{"id":66893,"date":"2006-07-17T11:19:00","date_gmt":"2006-07-17T11:19:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/07\/17\/how-can-i-get-the-names-of-10-randomly-selected-files-in-a-folder\/"},"modified":"2006-07-17T11:19:00","modified_gmt":"2006-07-17T11:19:00","slug":"how-can-i-get-the-names-of-10-randomly-selected-files-in-a-folder","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-get-the-names-of-10-randomly-selected-files-in-a-folder\/","title":{"rendered":"How Can I Get the Names of 10 Randomly-Selected Files in a Folder?"},"content":{"rendered":"<p><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\"> \n<P>Hey, Scripting Guy! How can I get the names of 10 randomly-selected files in a folder? I need to do that so I can test and verify our backup and restore policies.<BR><BR>&#8212; CS<\/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, CS. You know, if you\u2019re interested in things that are random, haphazard, arbitrary, or downright chaotic, well, you came to the right place. For example, any time we Scripting Guys have a contest we select the winners via random drawing. When it comes time to write a new <I>Hey, Scripting Guy!<\/I> column we randomly choose a question to answer. Remember the Butterfly Effect, the idea that a random butterfly flapping its wings in Brazil could be responsible for a blizzard in New England? That was our butterfly!<\/P>\n<TABLE id=\"E3C\" 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 to the people of New England<\/B>. The Scripting Guys apologize for any inconvenience the blizzard might have caused. We still can\u2019t figure out how that butterfly got out of its jar.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>Now, admittedly, making it snow in New England isn\u2019t all that big of a deal; it\u2019s kind of like bragging that you can make it rain in Seattle. So can we do something <I>really<\/I> challenging, something like randomly grab file names from a folder? Surprisingly enough, it turns out that we can:<\/P><PRE class=\"codeSample\">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:\\Scripts&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)<\/p>\n<p>intFiles = colFiles.Count<\/p>\n<p>Set objDictionary = CreateObject(&#8220;Scripting.Dictionary&#8221;)<\/p>\n<p>intHighNumber = intFiles\nintLowNumber = 1<\/p>\n<p>For i = 1 to 10\n    x = 0\n    Do Until x = 1\n        Randomize\n        intNumber = Int((intHighNumber &#8211; intLowNumber + 1) * Rnd + intLowNumber)\n        If objDictionary.Exists(intNumber) Then\n            x = 0\n        Else\n            objDictionary.Add intNumber, intNumber\n            x = 1\n        End If\n    Loop\nNext<\/p>\n<p>i = 1<\/p>\n<p>For Each objFile in colFiles\n    If objDictionary.Exists(i) Then\n        Wscript.Echo objFile.Name\n    End If\n    i = i + 1\nNext\n<\/PRE>\n<P>Yes, you\u2019re right: this script <I>is<\/I> a bit crazy-looking, at least at first glance. So let\u2019s see what we can do to clear up the confusion a little.<\/P>\n<P>We actually start off in straightforward fashion: we simply connect to the WMI service on the local computer (although we could just as easily connect to the WMI service on a remote computer). We then use this line of code to retrieve a collection of all the files found in the folder C:\\Scripts:<\/P><PRE class=\"codeSample\">Set colFiles = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Scripts&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)\n<\/PRE>\n<P>Once we have that collection in tow we then use the value of the <B>Count<\/B> property to determine the total number of files in that folder, a value we store in a variable named intFiles:<\/P><PRE class=\"codeSample\">intFiles = colFiles.Count\n<\/PRE>\n<P>Why do we need to know the total number of files in the folder? Hang on; we\u2019ll explain that in just a moment. Finally, we create an instance of the <B>Scripting.Dictionary<\/B> object:<\/P><PRE class=\"codeSample\">Set objDictionary = CreateObject(&#8220;Scripting.Dictionary&#8221;)\n<\/PRE>\n<P>Why do we do <I>that<\/I>? Be patient; sooner or later this will all make sense.<\/P>\n<P>Or so we hope.<\/P>\n<P>We\u2019re now ready to start generating 10 random numbers, numbers we\u2019ll use to indicate the files that we want to grab from the folder. To do that, our first step is to assign values to a pair of variables:<\/P><PRE class=\"codeSample\">intHighNumber = intFiles\nintLowNumber = 1\n<\/PRE>\n<P>As you can see, we assign the number of files in the folder (the value of intFiles) to intHighNumber and the value 1 to the variable intLowNumber. Why? Well, we need to pick a random number, and that random number needs to fall between two values: 1 and the total number of files in the folder. For example, if we have 39 files in the folder we need to randomly pick a number between 1 and 39; in a case like that it doesn\u2019t do us any good to pick file number -83 or file number 765. After all, how could we randomly select file 765 if there are only 39 files to begin with?<\/P>\n<TABLE id=\"EJE\" 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>. Yes, we could have used the variable intFiles in the equation, and we could have hard-coded the value 1 into the equation. We used the variables intHighNumber and intLowNumber to help make it clear what those values represent.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>That brings us to this big, bad For Next loop:<\/P><PRE class=\"codeSample\">For i = 1 to 10\n    x = 0\n    Do Until x = 1\n        Randomize\n        intNumber = Int((intHighNumber &#8211; intLowNumber + 1) * Rnd + intLowNumber)\n        If objDictionary.Exists(intNumber) Then\n            x = 0\n        Else\n            objDictionary.Add intNumber, intNumber\n            x = 1\n        End If\n    Loop\nNext\n<\/PRE>\n<P>What we\u2019re doing here is looping around 10 times; each time through the loop we\u2019ll generate a new random number. Inside the loop the very first thing we do is set the value of a counter variable named x to 0 (and, yes, we\u2019ll explain why in just a second). We then set up a Do Until loop that runs into x = 1. (Don\u2019t panic; we\u2019re getting to that, too.)<\/P>\n<P>Inside the Do Until loop we use these two lines of code to generate a random number between 1 and the total number of files in the folder:<\/P><PRE class=\"codeSample\">Randomize\nintNumber = Int((intHighNumber &#8211; intLowNumber + 1) * Rnd + intLowNumber)\n<\/PRE>\n<TABLE id=\"EZE\" 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>. We\u2019re not going to explain the random number process in any detail today; for more information, see this not-so-randomly selected <A href=\"http:\/\/null\/technet\/scriptcenter\/resources\/qanda\/may05\/hey0518.mspx\"><B>Hey, Scripting Guy! column<\/B><\/A>.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>We now have a random number (let\u2019s say it\u2019s 13). Because we want to randomly select 10 files, that means we need to generate 10 random numbers. That also means we need to temporarily store our random numbers until we have all 10 of them. We decided that the easiest way to do that is to store all the random numbers in an instance of the <A href=\"http:\/\/null\/technet\/scriptcenter\/guide\/sas_scr_ildk.mspx\"><B>Dictionary object<\/B><\/A>.<\/P>\n<P>Of course, there <I>is<\/I> a catch here: items in the Dictionary must be unique (we can\u2019t store the number 13 multiple times). Because of that we use the <B>Exists<\/B> method to see if the random number we just generated is already in the Dictionary:<\/P><PRE class=\"codeSample\">If objDictionary.Exists(intNumber) Then\n<\/PRE>\n<P>Let\u2019s say that it is. That means we can\u2019t add the number to the Dictionary again; remember, no duplicate items. Therefore, we set the value of x to 0; because x is 0 that means our Do Until loop will simply run again, and continue to run until we generate a random number that <I>isn\u2019t<\/I> in the Dictionary. As soon as we find such a number we execute these two lines of code:<\/P><PRE class=\"codeSample\">objDictionary.Add intNumber, intNumber\nx = 1\n<\/PRE>\n<P>The first line simply adds the randomly-generated number to the Dictionary (using the number itself as both the Dictionary key and item). After that we set the value of x to 1. Very good; that\u2019s <I>exactly<\/I> why we do that. As you figured out, our Do Until loop is designed to run until x equals 1. Now that x <I>does<\/I> equal 1, we\u2019ll break out of the loop and return to the next iteration of the For Next loop. Make sense? Good. This process continues until we have 10 items (numbers) in the Dictionary.<\/P>\n<P>That leaves us with this block of code, which is where we actually grab the 10 file names:<\/P><PRE class=\"codeSample\">i = 1<\/p>\n<p>For Each objFile in colFiles\n    If objDictionary.Exists(i) Then\n        Wscript.Echo objFile.Name\n    End If\n    i = i + 1\nNext\n<\/PRE>\n<P>The first thing we do here is set the value of the counter variable i to 1; we\u2019ll use this variable to track which file (i.e., file 1, file 2, file 3, etc.) we\u2019re dealing with. (We set i equal to 1 simply because we\u2019ll be starting with the first file in the collection.) After setting up a For Each loop to walk through the collection of files we then encounter this line of code:<\/P><PRE class=\"codeSample\">If objDictionary.Exists(i) Then\n<\/PRE>\n<P>All we\u2019re doing here is checking to see if the value of i (which, the first time through the loop, is equal to 1) is in the Dictionary. What if it is? Well, then that can only mean one thing: 1 is one of our randomly-generated numbers. In turn, we echo back the <B>Name<\/B> of the first file in the collection. If number 1 is <I>not<\/I> in the Dictionary then we don\u2019t do anything at all. We only echo back the names of the files whose file number can be found in the Dictionary.<\/P>\n<P>Regardless of whether or not the value exists in the Dictionary we increment i by 1 (making i equal to 2), loop around, and check to see if the value 2 is in the Dictionary. This continues until we\u2019ve walked through the entire collection of files. When all is said and done, we should have a list of 10 randomly-selected file names:<\/P><PRE class=\"codeSample\">c:\\scripts\\book1.xls\nc:\\scripts\\employees.log\nc:\\scripts\\imapi.vbs\nc:\\scripts\\read-write.vbs\nc:\\scripts\\tee.txt\nc:\\scripts\\test.csv\nc:\\scripts\\test.txt\nc:\\scripts\\test.txt.doc\nc:\\scripts\\test.xml\nc:\\scripts\\x.txt\n<\/PRE>\n<P>Cool.<\/P>\n<P>Hey, that\u2019s OK, CS: no need to thank us. Like we said, we enjoy experimenting with randomness and with Chaos Theory. For example, we recently tried to determine, once and for all, whether a million monkeys typing on a million computers could produce the complete works of Shakespeare. As it turned out, they couldn\u2019t. But at least we <I>did <\/I>get the latest <A href=\"http:\/\/null\/technet\/scriptcenter\/resources\/begin\/ss0706.mspx\"><B>Sesame Script<\/B><\/A> column out of the deal. Thanks, guys!<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I get the names of 10 randomly-selected files in a folder? I need to do that so I can test and verify our backup and restore policies.&#8212; CS Hey, CS. You know, if you\u2019re interested in things that are random, haphazard, arbitrary, or downright chaotic, well, you came to 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":[18,715,38,11,3,4,12,5,6],"class_list":["post-66893","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-arrays-hash-tables-and-dictionary-objects","tag-associators-of","tag-files","tag-folders","tag-scripting-guy","tag-scripting-techniques","tag-storage","tag-vbscript","tag-wmi"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! How can I get the names of 10 randomly-selected files in a folder? I need to do that so I can test and verify our backup and restore policies.&#8212; CS Hey, CS. You know, if you\u2019re interested in things that are random, haphazard, arbitrary, or downright chaotic, well, you came to the [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66893","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=66893"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/66893\/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=66893"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=66893"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=66893"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}