{"id":53873,"date":"2009-04-28T23:17:00","date_gmt":"2009-04-28T23:17:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2009\/04\/28\/hey-scripting-guy-how-can-i-use-the-windows-powershell-equivalent-of-the-vbscript-whilewend-loop\/"},"modified":"2009-04-28T23:17:00","modified_gmt":"2009-04-28T23:17:00","slug":"hey-scripting-guy-how-can-i-use-the-windows-powershell-equivalent-of-the-vbscript-whilewend-loop","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-use-the-windows-powershell-equivalent-of-the-vbscript-whilewend-loop\/","title":{"rendered":"Hey, Scripting Guy! How Can I Use the Windows PowerShell Equivalent of the VBScript While\u2026Wend Loop?"},"content":{"rendered":"<p><H2><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\"> <\/H2>\n<P>Hey, Scripting Guy! I have been using VBScript for a long time. One of my favorite language statements in VBScript is the <B>While\u2026Wend<\/B> loop. It is easy to use and easy to understand. Is there an equivalent command in Windows PowerShell?<BR><BR>&#8211; HS<\/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\"> \n<P>Hi HS,<\/P>\n<P>WE never did use the <B>While\u2026Wend<\/B> loop very much. WE generally used the <B>Do\u2026While\u2026Loop<\/B> construction instead. We have a good <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/begin\/default.mspx\" target=\"_blank\">Sesame Script article<\/A> that talks about five ways of performing looping in VBScript. In fact, most of the scripts we have written over the years at the Script Center did not use the <B>While\u2026Wend<\/B> loop. That does not mean that it is wrong, nor is one any better than the other as long as it does the job that you want to perform. It is all about choices. Sometimes, these choices can be confusing. When you walk into a chocolate store, you may think it is a bit unnecessary that they have 50 different kinds laid out in all the display cases. We know that we\u2019ll have the giant peanut butter cup; we are in and out in less than a minute. However, we have friends who could spend a complete day shopping in a chocolate store. So we can each experience the same activity in a different way. As long as one is happy, it is all that is important. If you want to use the <B>While\u2026Wend<\/B> loop in VBScript, go ahead. If you want to use the same kind of construction in Windows PowerShell, guess what? We can accommodate you!<\/P>\n<TABLE class=\"dataTable\" id=\"ELD\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD class=\"\">\n<P class=\"lastInCell\">This week we are looking at scripting Windows PowerShell. Windows PowerShell is installed by default on Windows Server 2008 R2 and Windows 7. It is an optional installation on Windows Server 2008, and a download for <A href=\"http:\/\/www.microsoft.com\/downloads\/details.aspx?displaylang=en&amp;FamilyID=c6ef4735-c7de-46a2-997a-ea58fdfcba63\" target=\"_blank\">Windows Vista<\/A>, <A href=\"http:\/\/www.microsoft.com\/downloads\/details.aspx?displaylang=en&amp;FamilyID=6ccb7e0d-8f1d-4b97-a397-47bcc8ba3806\" target=\"_blank\">Windows XP<\/A>, and <A href=\"http:\/\/www.microsoft.com\/downloads\/details.aspx?displaylang=en&amp;FamilyID=10ee29af-7c3a-4057-8367-c9c1dab6e2bf\" target=\"_blank\">Windows Server 2003<\/A>. The <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/hubs\/msh.mspx\" target=\"_blank\">Windows PowerShell Scripting Hub<\/A> is a good place to start using Windows PowerShell. An excellent book for learning Windows PowerShell is the Microsoft Press book, <A href=\"http:\/\/www.microsoft.com\/MSPress\/books\/authors\/auth10329.aspx\" target=\"_blank\">Microsoft Windows PowerShell Step by Step<\/A>. This book has many hands-on labs and uses real-world examples to show the use of Windows PowerShell.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>For those who may not be familiar with the <B>While\u2026Wend<\/B> loop in VBScript, we took the time to write a quick VBScript to explain what we are talking about. The first thing the <B>WhileReadLineWend.vbs<\/B> script does is create an instance of the <B>FileSystemObject<\/B>, and store it in the <B>objFSO<\/B> variable. We then use the <B>OpenTextFile<\/B> method to open a test file, and store that object in the <B>objFile<\/B> variable. We then use the <B>While Not \u2026Wend<\/B> construction to read one line at a time from the text stream and display it on the screen. We continue to do this until we are at the end of the text stream object. A <B>While\u2026Wend<\/B> loop merely continues to operate as long as a condition is evaluated as true. In this example, as long as we are not at the end of the stream, we will continue to read the line from the text file. The <B>WhileReadLineWend.vbs<\/B> script is shown here.<\/P>\n<P><B>WhileReadLineWend.vbs<\/B><\/P><PRE class=\"codeSample\">Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objFile = objFSO.OpenTextFile(&#8220;C:\\fso\\testfile.txt&#8221;)<\/p>\n<p>While Not objFile.AtEndOfStream\n WScript.Echo objFile.ReadLine\nWend\n<\/PRE>\n<P>As you probably have already guessed, we have the same kind of construction available to us in Windows PowerShell. Incidentally, the <B>While<\/B> statement in Windows PowerShell works in a very similar manner to the one that you use in VBScript. In the <B>DemoWhileLessThan.ps1<\/B> script, we first initialize the variable <B>$i<\/B> to be equal to 0. We then use the <B>While<\/B> keyword to begin the <B>While<\/B> loop. In Windows PowerShell, we must include the condition that will be evaluated inside a set of parentheses. For this example, we determine the value of the <B>$i<\/B> variable with each pass through the loop. If the value of <B>$i<\/B> is less than the number 5, we will perform the action that is specified inside the braces (curly brackets) that set off the script block. <\/P>\n<P>In VBScript the condition that is evaluated is positioned on the same line with the <B>While<\/B> statement, but no parentheses are required. Although this is convenient from a typing perspective, it actually makes the code a bit confusing to read. In Windows PowerShell, the statement is outside the parentheses and the condition is clearly delimited by the parentheses. In VBScript the action that is performed is added between two words: <B>while<\/B> and <B>wend<\/B>. In Windows PowerShell, there is no <B>wend<\/B> statement, and the action to be performed is positioned inside a pair of braces. Although shocking at first to users coming from a VBScript background, the braces are always used to contain code. This is what is called a script block, and they are used everywhere. As soon as you are used to seeing them here, you will find them with other language statements too. The good thing is you do not have to look for items such as the keyword <B>Wend<\/B> or the keyword <B>Loop<\/B> (from <B>Do\u2026Loop<\/B> fame).<\/P>\n<P>In Windows PowerShell, there are two kinds of strings: literal strings and expanding strings. In the <B>DemoWhileLessThan.ps1<\/B> script, we use the expanding string (signified by using the double quotation mark, <B>\u201c<\/B> [the literal string uses the single quotation mark, <B>\u2018<\/B>]). We want to display the name of the variable, and we want to display the value that is contained in the variable. This is a perfect place to showcase the expanding string. In an expanding string, the value that is contained in a variable is displayed on the screen when a line is evaluated. As an example, consider the following code. We assign the value 12 to the variable <B>$i<\/B>. We then put <B>$i<\/B> inside a pair of double quotation marks to make an expanding string. When the line <B>\u201c$i is equal to $i\u201d<\/B> is evaluated, we get \u201c12 is equal to 12\u201d which while true is barely illuminating. This is shown&nbsp;here:<\/P><PRE class=\"codeSample\">PS C:\\&gt; $i = 12\nPS C:\\&gt; &#8220;$i is equal to $i&#8221;\n12 is equal to 12\nPS C:\\&gt;\n<\/PRE>\n<P>What we wanted to do is display both the name of the variable and the value that is contained inside it. In VBScript we would have to use concatenation. For this example to work, we have to use the literal string as seenhere: <\/P><PRE class=\"codeSample\">PS C:\\&gt; $i = 12\nPS C:\\&gt; &#8216;$i is equal to &#8216; + $i\n$i is equal to 12\nPS C:\\&gt;\n<\/PRE>\n<P>If we want to use the advantage of the expanding string, we have to suppress the expanding nature of the expanding string for the first variable. To do this, we use the escape character which is the backtick character. This is seen&nbsp;here:<\/P><PRE class=\"codeSample\">PS C:\\&gt; $i = 12\nPS C:\\&gt; &#8220;`$i is equal to $i&#8221;\n$i is equal to 12\nPS C:\\&gt;\n<\/PRE>\n<P>In the <B>DemoWhileLessThan.ps1<\/B> script, we use the expanding string to display our status message of the value of the <B>$i<\/B> variable during each trip through the <B>While<\/B> loop. We suppress the expanding nature of the expanding string for the first <B>$i<\/B> variable so that we can see which variable we are talking about. As soon as we have done this, we increment the value of the <B>$i<\/B> variable by one. To do this, we use the <B>$i++<\/B> syntax. This is identical to saying the following:<\/P><PRE class=\"codeSample\">$i = $i + 1<\/PRE>\n<P>The advantage is that the <B>$i++<\/B> syntax is less typing. The <B>DemoWhileLessThan.ps1<\/B> script is seen here:<\/P>\n<P><B>DemoWhileLessThan.ps1<\/B><\/P><PRE class=\"codeSample\">$i = 0\nWhile ($i -lt 5)\n {\n  &#8220;`$i equals $i. This is less than  5&#8221;\n  $i++ \n } #end while $i lt 5\n<\/PRE>\n<P>When you run the <B>DemoWhileLessThan.ps1<\/B> script, you receive the following&nbsp;output:<\/P><PRE class=\"codeSample\">$i equals 0. This is less than  5\n$i equals 1. This is less than  5\n$i equals 2. This is less than  5\n$i equals 3. This is less than  5\n$i equals 4. This is less than  5\nPS C:\\&gt;\n<\/PRE>\n<P>Now that you know how to use the <B>While<\/B> loop, let\u2019s examine the <B>WhileReadLine.ps1<\/B> script. The first thing we do is initialize the <B>$i<\/B> variable and set it equal to <B>0<\/B>. We then use the b cmdlet to read the contents of the <B>T<\/B><B>estfile.txt<\/B> and to store the contents into the <B>$fileContents<\/B> variable. The <B>Testfile.txt<\/B> file is shown here:<\/P><IMG height=\"159\" alt=\"Image of using the Get-Content cmdlet to read the Testfile.txt file\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/april\/hey0428\/hsg-04-28-01.jpg\" width=\"500\" border=\"0\"> \n<P>&nbsp;<\/P>\n<P>Now we use the <B>While<\/B> statement to loop through the contents of the text file. We do this as long as the value of the <B>$i<\/B> variable is less than or equal to the number of lines in the text file. The number of lines in the text file is represented by the <B>length<\/B> property. Inside the script block, we treat the contents of the <B>$fileContents<\/B> variable as if it is an array (which it is), and we use the <B>$i<\/B> variable to index into the array to print the value of each line in the <B>$fileContents<\/B> variable. We then increment the value of the <B>$i<\/B> variable by one. The <B>WhileReadLine.ps1<\/B> script is shown here:<\/P>\n<P><B>WhileReadLine.ps1<\/B><\/P><PRE class=\"codeSample\">$i = 0\n$fileContents = Get-Content -path C:\\fso\\testfile.txt\nWhile ( $i -le $fileContents.length )\n {\n  $fileContents[$i]\n  $i++\n }\n<\/PRE>\n<P>If&nbsp;you are thinking the <B>WriteReadLine.ps1<\/B> script is a bit difficult, in reality it is about the same difficulty level as the VBScript version. The difference is we resorted to using arrays to work with the content we received from the <B>Get-Content<\/B> cmdlet. The VBScript version uses a <B>FileSystemObject<\/B> and a <B>TextStreamObject<\/B> to work with the data. In reality, we would not have to use a script exactly like the <B>WhileReadLine.ps1<\/B> script to read the contents of the text file. This is because the <B>Get-Content<\/B> cmdlet does this for us automatically. All we really have to do to display the contents of the <B>TestFile.txt<\/B> is use <B>Get-Content<\/B>. This is shown here:<\/P><PRE class=\"codeSample\">Get-Content \u2013path c:\\fso\\TestFile.txt<\/PRE>\n<P>The results of the command are shown here:<\/P><IMG height=\"140\" alt=\"Image of the Get-Content cmdlet reading and displaying content from a text file\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/april\/hey0428\/hsg-04-28-02.jpg\" width=\"500\" border=\"0\"> \n<P>&nbsp;<\/P>\n<P>By not storing the results of the command in a variable, the contents are automatically displayed. The <B>Get-Content<\/B> command can be further shortened by using the <B>gc<\/B> alias (short name for the <B>Get-Content<\/B> cmdlet) and by omitting the name of the <B>\u2013path<\/B> parameter (which is the default parameter). When we do this, we create a command that resembles the following:<\/P><PRE class=\"codeSample\">GC c:\\fso\\TestFile.txt<\/PRE>\n<P>To find the available aliases for the <B>Get-Content<\/B> cmdlet, I used the <B>Get-Alias<\/B> cmdlet to produce a listing of all the aliases that are defined in the current session. I then pipelined the results of the command to the <B>Where-Object<\/B> and looked for definitions that match <B>Get-Content<\/B>. Here is the command and the output Ireceived:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Alias | where-object { $_.definition -eq &#8216;get-content&#8217;}<\/p>\n<p>CommandType     Name                            Definition\n&#8212;&#8212;&#8212;&#8211;     &#8212;-                            &#8212;&#8212;&#8212;-\nAlias           cat                             Get-Content\nAlias           gc                              Get-Content\nAlias           type                            Get-Content\n<\/PRE>\n<P>We have shown you that you can use the <B>While<\/B> statement in Windows PowerShell. We have also shown that occasionally you do not have to use the looping behavior because some cmdlets will automatically display information. Finally, we showed you how you can find aliases for cmdlets you frequently use. Join us tomorrow as we continue with Introduction to Windows PowerShell Scripting Week. Until then, take care.<\/P>\n<P>&nbsp;<\/P>\n<P><B>Ed Wilson and Craig Liebendorfer, Scripting Guys<\/B><\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I have been using VBScript for a long time. One of my favorite language statements in VBScript is the While\u2026Wend loop. It is easy to use and easy to understand. Is there an equivalent command in Windows PowerShell?&#8211; HS Hi HS, WE never did use the While\u2026Wend loop very much. WE generally [&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":[51,3,4,45],"class_list":["post-53873","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-getting-started","tag-scripting-guy","tag-scripting-techniques","tag-windows-powershell"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I have been using VBScript for a long time. One of my favorite language statements in VBScript is the While\u2026Wend loop. It is easy to use and easy to understand. Is there an equivalent command in Windows PowerShell?&#8211; HS Hi HS, WE never did use the While\u2026Wend loop very much. WE generally [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/53873","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=53873"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/53873\/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=53873"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=53873"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=53873"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}