{"id":52023,"date":"2009-11-12T00:01:00","date_gmt":"2009-11-12T00:01:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2009\/11\/12\/hey-scripting-guy-how-can-i-create-variables-in-windows-powershell\/"},"modified":"2009-11-12T00:01:00","modified_gmt":"2009-11-12T00:01:00","slug":"hey-scripting-guy-how-can-i-create-variables-in-windows-powershell","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-create-variables-in-windows-powershell\/","title":{"rendered":"Hey, Scripting Guy! How Can I Create Variables in Windows PowerShell?"},"content":{"rendered":"<p><!-- AddThis Button BEGIN --><a class=\"addthis_button\" href=\"http:\/\/www.addthis.com\/bookmark.php?v=250&amp;pub=scriptingguys\"><img decoding=\"async\" alt=\"Bookmark and Share\" src=\"http:\/\/s7.addthis.com\/static\/btn\/v2\/lg-share-en.gif\" width=\"125\" height=\"16\"><\/a><!-- AddThis Button END --><\/p>\n<p class=\"MsoNormal\">&nbsp;<\/p>\n<p class=\"Readeraidonly\"><img decoding=\"async\" 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 class=\"MsoNormal\">Hey, Scripting Guy! In VBScript, it was easy to create a variable; all I had to do was use the <b>DIM<\/b> statement. I did not need to specify a type or a value or anything. I just used <b>DIM<\/b> and the variable would be created. How do I create variables in Windows PowerShell? Please tell me you haven&rsquo;t made it harder.<\/p>\n<p class=\"MsoNormal\">&#8212; TL<\/p>\n<p class=\"MsoNormal\"><img decoding=\"async\" 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\">&nbsp;Hello TL, <\/p>\n<p class=\"MsoNormal\">Microsoft Scripting Guy Ed Wilson here. Today has been a very eventful day for me. I have had four meetings&mdash;all of which were essential. One meeting in particular, the meeting with Karen who helps us manage the Script Center Web site was especially productive. We are talking about modifying the <a href=\"http:\/\/bit.ly\/microsoftscriptcenter\"><font face=\"Segoe\">Script Center home page<\/font><\/a> to make it more user-friendly (don&rsquo;t worry, it will not be a radical change like our recent migration). We all had some good ideas about what needs to be done, but I think Karen wins the best suggestion award for her idea to&hellip;well, you will just have to wait and see. I can tell you that we are really psyched! <\/p>\n<p class=\"MsoNormal\">Over the course of the last five months, we have gone from a great Web site with no bells or whistles to a great Web site with so much more available to us in terms of making the site easier for you to use. However, we won&rsquo;t ever use any technical Web gewgaws just for the sake of using gewgaws. I am listening to <a href=\"http:\/\/en.wikipedia.org\/wiki\/Whitesnake\"><font face=\"Segoe\">White Snake<\/font><\/a> (the early stuff, not the later commercial dross) on my Zune, and sipping a cup of <a href=\"http:\/\/en.wikipedia.org\/wiki\/Rooibos\"><font face=\"Segoe\">Rooibos tea<\/font><\/a> and nibbling on a small piece of 85 percent cacao from France while I review the e-mail sent to <a href=\"http:\/\/blogs.technet.commailto:scripter@microsoft.com\"><span><font face=\"Segoe\">scripter@microsoft.com<\/font><\/span><\/a>.<\/p>\n<p class=\"Readeraidonly\">Note: Portions of today&#8217;s Hey, Scripting Guy! post are excerpted from the Microsoft Press book, <i>Windows PowerShell 2.0 Best Practices<\/i> by Ed Wilson. The book is <a href=\"http:\/\/bit.ly\/edwilsonbestpractices\">available for pre-order<\/a>.<\/p>\n<p class=\"MsoNormal\">TL, as with creating aliases (which was discussed in <a href=\"http:\/\/blogs.technet.com\/heyscriptingguy\/archive\/2009\/11\/09\/hey-scripting-guy-tell-me-about-aliases-in-windows-powershell.aspx\"><span>Monday&rsquo;s Hey Scripting Guy! post<\/span><\/a>), there are several different ways to create a variable and to assign a value to it. You can use the <b>New-Item<\/b> cmdlet on the variable drive as seen here:<\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">New-Item -Name temp -Value $env:TEMP -Path variable:<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"MsoNormal\">You could also use the <b>Set-Item<\/b> cmdlet to do this. The advantage to the <b>Set-Item<\/b> cmdlet is that it does not generate an error if the variable already exists. Here is an example of using the <b>Set-item<\/b> cmdlet to create a variable. One thing to keep in mind is that the <b>Set-item<\/b> cmdlet does not have a parameter named <b>&ndash;name:<\/b> <\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">Set-Item -Value $env:TEMP -Path variable:temp<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"MsoNormal\">Neither the <b>New-Item<\/b> nor the <b>Set-Item<\/b> cmdlet has the ability to specify the <b>option<\/b> or the <b>description<\/b> parameter. With variables this is an important distinction because you cannot create a constant and you cannot create a read-only variable without using either <b>Set-Variable<\/b> or <b>New-Variable<\/b>. If a variable already exists and you use the <b>Set-Variable<\/b> cmdlet, the value of the variable will be overwritten if it has not been marked read-only or constant. If it is read-only, you can still modify the value of it by specifying the <b>Force<\/b> parameter. If the variable is marked as a constant, the only way to modify the value of the variable is to close the Windows PowerShell console and start over with a new value. <\/p>\n<p class=\"MsoNormal\">You can also create a variable and assign a value to it at the same time. This technique if often used when the value to be stored in the variable is the result of a calculation or concatenation. In this example, we decide to create a variable named <b>$wuLog<\/b> to store the path to the Windows Update log, which is stored in a rather obscure location in the user&rsquo;s local Application Data folder. Though there is an environmental variable for local application data, the path continues to go on for a couple of levels before terminating in the WindowsUpdate.log file. As a best practice when building file paths, you should use the path cmdlets such as <b>Join-Path<\/b> to avoid concatenation errors. By using the environmental <b>localappdata<\/b> variable and <b>Join-Path<\/b> with the <b>&ndash;resolve<\/b> switched parameter, we also have a formula that will store the path to the WindowsUpdate log file on any user&rsquo;s computer. This is exactly the kind of variable you would want to create and store in a user&rsquo;s Windows PowerShell profile. This command is seen here. <\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">PS C:&gt; $wuLog = Join-Path -Path $env:LOCALAPPDATA `<br>-ChildPath microsoftwindowswindowsupdate.log -Resolve<br>PS C:&gt; $wuLog<br>C:Usersedwils.NORTHAMERICAAppDataLocalmicrosoftwindowswindowsupdate.log<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"MsoNormal\">When using a variable to hold a computed value, you are not limited to using a direct value assignment. You can use the <b>New-Variable<\/b> cmdlet to perform exactly the same task: <\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">PS C:&gt; New-Variable -Name wulog -Value (Join-Path -Path $env:LOCALAPPDATA `<br>-ChildPath microsoftwindowswindowsupdate.log -Resolve)<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"Readeraidonly\">When using the <b>New-Variable<\/b> cmdlet to create a variable that will hold a computed result, you will often need to use parentheses to force the value to be created before attempting to assign it to the <b>Value<\/b> parameter. You may see an error about some missing or invalid parameter. This is because when the <b>New-Variable <\/b>cmdlet sees a parameter outside of a set of parentheses, it attempts to locate that parameter. An example of such an error is seen in the following image.<\/p>\n<p class=\"Fig-Graphic\"><img decoding=\"async\" title=\"Image of missing parameter error\" alt=\"Image of missing parameter error\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/november\/hey1112\/hsg-11-12-09-1.jpg\" width=\"600\" height=\"502\"><\/p>\n<p class=\"Fig-Graphic\">&nbsp;<\/p>\n<p class=\"MsoNormal\">You can also use some of the automatic variables when creating variables for your profile. A large number of applications place files in the user&rsquo;s documents directory. Though this is convenient for applications and for users who access the documents location via a link on the Start menu, it is nearly impossible to locate via the command line. An additional problem is that the Documents folder may not be displayed on the Start menu of the user. As seen in the following image, the folder may have been deselected:<\/p>\n<p class=\"Fig-Graphic\"><img decoding=\"async\" title=\"Image of deselected Documents folder\" alt=\"Image of deselected Documents folder\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/november\/hey1112\/hsg-11-12-09-2.jpg\" width=\"381\" height=\"468\"><\/p>\n<p class=\"Fig-Graphic\">&nbsp;<\/p>\n<p class=\"MsoNormal\">To facilitate ease of access to the user&rsquo;s Documents folder, you may decide to create a variable that could easily be used to refer to the path. This is another good opportunity to use the <b>Join-Path<\/b> cmdlet to aid in building the location to the Documents folder. There is an automatic variable that already points to the user&#8217;s home directory. The home directory on my Windows Vista laptop points to the <b>%username%<\/b> folder under the user&rsquo;s folder. This is seen here:<\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">PS C:&gt; $home<br>C:Usersedwils.NORTHAMERICA<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"MsoNormal\">Because the Documents folder is located under this home directory, as seen in the following image, we can add to this location and build the path to the documents directory:<\/p>\n<p class=\"Fig-Graphic\"><img decoding=\"async\" title=\"Image of Documents folder under home directory\" alt=\"Image of Documents folder under home directory\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/november\/hey1112\/hsg-11-12-09-3.jpg\" width=\"600\" height=\"447\"><\/p>\n<p class=\"MsoNormal\"><br>By using the <b>New-Variable<\/b> cmdlet, you can specify the <b>Value<\/b> parameter, which is contained in a set of parentheses because of the need to resolve the value of the <b>Join-Path<\/b> command before assigning it to the <b>docs<\/b> variable. The variable will be read-only, which allows you to modify the variable if needed, but it will also be protected from accidental deletion or modification. The <b>Description<\/b> parameter provides an easy way to keep track of all the custom variables. This line of code is shown here:<\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">New-Variable -Name docs -Value (Join-Path -Path $home -ChildPath documents) `<br>-Option readonly -Description &#8220;MrEd Variable&#8221;<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"Readeraidonly\">When I was first learning Windows PowerShell, I was often frustrated when I attempted to use the <b>New-Variable<\/b>, <b>Set-Variable<\/b>, and <b>Remove-Variable<\/b> cmdlets because a variable is prefixed with the dollar sign when working at the command line, but the name parameter does not use the dollar sign as part of the name of the variable. <\/p>\n<p class=\"MsoNormal\">Another way to obtain the path to the Documents folder is to use the <b>WshShell<\/b> object from VBScript fame. Because Windows PowerShell provides easy access to Component Object Model (COM) objects, there is no reason to avoid these devices. One way to use this COM object is to create and use the object all in the same line. This is seen here:<\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">$docs = (New-Object -ComObject Wscript.Shell).specialFolders.item(&#8220;MyDocuments&#8221;)<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"MsoNormal\">From a best practice standpoint, there are at least two problems with the above syntax. The most obvious issue is that it is not very readable. While this is rather common usage, it would better to split the command into two lines of code as seen here:<\/p>\n<p class=\"CodeBlock\"><span><font face=\"Lucida Sans Typewriter\">$wshShell = New-Object -ComObject Wscript.Shell<br>$docs = $wshShell.SpecialFolders.Item(&#8220;MyDocuments&#8221;)<\/p>\n<p><\/font><\/span><\/p>\n<p class=\"MsoNormal\">&nbsp;<\/p>\n<p class=\"MsoNormal\">Well, TL, this should get you started working with variables in Windows PowerShell. Join us tomorrow as we open the virtual mail bag and answer questions that require only shorter answers. <\/p>\n<p class=\"MsoNormal\">If you want to know exactly what we will be looking at tomorrow, follow us on <a href=\"http:\/\/bit.ly\/scriptingguystwitter\" target=\"_blank\"><font face=\"Segoe\">Twitter<\/font><\/a> or <a href=\"http:\/\/bit.ly\/scriptingguysfacebook\" target=\"_blank\"><font face=\"Segoe\">Facebook<\/font><\/a>. If you have any questions, send e-mail to us at <a href=\"http:\/\/blogs.technet.commailto:scripter@microsoft.com\" target=\"_blank\"><font face=\"Segoe\">scripter@microsoft.com<\/font><\/a> or post them on the <a href=\"http:\/\/bit.ly\/scriptingforum\" target=\"_blank\"><font face=\"Segoe\">Official Scripting Guys Forum<\/font><\/a>. See you tomorrow. Until then, keep on scripting!<\/p>\n<p class=\"MsoNormal\">&nbsp;<\/p>\n<p><b><span>Ed Wilson and Craig Liebendorfer, Scripting Guys<\/span><\/b><\/p>\n<p class=\"MsoNormal\">&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>&nbsp; Hey, Scripting Guy! In VBScript, it was easy to create a variable; all I had to do was use the DIM statement. I did not need to specify a type or a value or anything. I just used DIM and the variable would be created. How do I create variables in Windows PowerShell? Please [&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,45],"class_list":["post-52023","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-getting-started","tag-scripting-guy","tag-windows-powershell"],"acf":[],"blog_post_summary":"<p>&nbsp; Hey, Scripting Guy! In VBScript, it was easy to create a variable; all I had to do was use the DIM statement. I did not need to specify a type or a value or anything. I just used DIM and the variable would be created. How do I create variables in Windows PowerShell? Please [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/52023","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=52023"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/52023\/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=52023"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=52023"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=52023"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}