{"id":1643,"date":"2010-02-19T22:18:50","date_gmt":"2010-02-20T03:18:50","guid":{"rendered":"http:\/\/www.bhargavs.com\/index.php\/powershell\/2010\/02\/powershell-variables-and-scopes\/"},"modified":"2010-02-19T22:18:50","modified_gmt":"2010-02-20T03:18:50","slug":"powershell-variables-and-scopes","status":"publish","type":"post","link":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/","title":{"rendered":"PowerShell Variables and scopes"},"content":{"rendered":"<p>I was helping someone with a profile script. The script is supposed to connect to a remote Exchange 2010 server using PowerShell v2.0 when it is launched.<\/p>\n<p>The script had a function which is called upon when profile is loaded. The function looked like the following:<\/p>\n<pre lang=\"PowerShell\" escaped=\"true\">\nfunction connect-remotely()\n\n{\n      if ($server)\n      {\n            $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http:\/\/$server\/PowerShell\/ -Authentication Kerberos\n            Import-PSSession $Session\n            write-warning 'Do not forget to run Remove-PSSession $Session'\n      }\n      else\n      {\n            $server = read-host \"Server name\"\n            connect-remotely $server\n      }\n}\n<\/pre>\n<p>The $session variable in this instance gets created and populated within the function. The problem, however, is not visible until a bit later. When we were done with our remote session, we tried to remove session using Remove-PSSession $session but encountered an error which indicated that $session has null value.<\/p>\n<p>Why did that happen? That\u2019s where I needed to understand how scopes work. The PowerShell session is created when we launch PowerShell. When the function is executed, a child scope is created. The $session variable is created within child scope. All is fine until after the function completes execution and exits. At this time, $session variable value becomes null since the scope in which it was created is no longer applicable.<\/p>\n<p>But wait, don\u2019t we need the object stored in that variable to remove session successfully? We sure do. So how do we address this?<\/p>\n<p>This can be accomplished using one of the two ways:<\/p>\n<p>1. Define the variable as global. This will make the variable available in all scopes including the one created by function and the parent scopes. Here\u2019s how you can do it:<\/p>\n<pre lang=\"PowerShell\" escaped=\"true\">\n$Global:Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http:\/\/$server\/PowerShell\/ -Authentication Kerberos\n<\/pre>\n<p>2. Second option (I like it better) is to define scope. I used New-Variable as describe below when creating $session within function and scoping it to value of 1:<\/p>\n<pre lang=\"PowerShell\" escaped=\"true\">\nNew-Variable -Name Session -Value (New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http:\/\/$server\/PowerShell\/ -Authentication Kerberos) -Scope 1\n<\/pre>\n<p>When you scope any variable, value 0 means the scope in which it was created. 1 means parent scope, 2 is grand parent and so on. By defining scope of 1, I made the variable available to parent scope of the function which is where I was running Remove-PSSession. As anyone can guess, both methods allowed me to successfully remove session as the variable $session stayed behind populated instead of becoming null.<\/p>\n<p>Hopefully this will help you understand how scope can help in certain situations. For better understanding of scopes, head out to <a href=\"http:\/\/technet.microsoft.com\/en-us\/library\/dd315289.aspx\">TechNet<\/a> as it contains lot more information about scopes which is not in scope of this post\u2026 get it? \ud83d\ude09<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I was helping someone with a profile script. The script is supposed to connect to a remote Exchange 2010 server using PowerShell v2.0 when it is launched. The script had [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"pgc_sgb_lightbox_settings":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[52,19],"tags":[213],"class_list":["post-1643","post","type-post","status-publish","format-standard","hentry","category-exchange-2010","category-powershell","tag-powershell-variable-scope"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.6 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>PowerShell Variables and scopes - Bhargav&#039;s IT Playground<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PowerShell Variables and scopes - Bhargav&#039;s IT Playground\" \/>\n<meta property=\"og:description\" content=\"I was helping someone with a profile script. The script is supposed to connect to a remote Exchange 2010 server using PowerShell v2.0 when it is launched. The script had [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/\" \/>\n<meta property=\"og:site_name\" content=\"Bhargav&#039;s IT Playground\" \/>\n<meta property=\"article:published_time\" content=\"2010-02-20T03:18:50+00:00\" \/>\n<meta name=\"author\" content=\"Bhargav\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Bhargav\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/\"},\"author\":{\"name\":\"Bhargav\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#\\\/schema\\\/person\\\/28f6d8c9b29f3a879483d65fc2ab5e26\"},\"headline\":\"PowerShell Variables and scopes\",\"datePublished\":\"2010-02-20T03:18:50+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/\"},\"wordCount\":372,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#\\\/schema\\\/person\\\/28f6d8c9b29f3a879483d65fc2ab5e26\"},\"keywords\":[\"PowerShell Variable Scope\"],\"articleSection\":[\"Exchange 2010\",\"PowerShell\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/\",\"url\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/\",\"name\":\"PowerShell Variables and scopes - Bhargav&#039;s IT Playground\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#website\"},\"datePublished\":\"2010-02-20T03:18:50+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/02\\\/19\\\/powershell-variables-and-scopes\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/bhargavs.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PowerShell Variables and scopes\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#website\",\"url\":\"https:\\\/\\\/bhargavs.com\\\/\",\"name\":\"Bhargav's IT Playground\",\"description\":\"Passion for Technology. Power of Collaboration.\",\"publisher\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#\\\/schema\\\/person\\\/28f6d8c9b29f3a879483d65fc2ab5e26\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/bhargavs.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#\\\/schema\\\/person\\\/28f6d8c9b29f3a879483d65fc2ab5e26\",\"name\":\"Bhargav\",\"logo\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/bhargavs.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"PowerShell Variables and scopes - Bhargav&#039;s IT Playground","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/","og_locale":"en_US","og_type":"article","og_title":"PowerShell Variables and scopes - Bhargav&#039;s IT Playground","og_description":"I was helping someone with a profile script. The script is supposed to connect to a remote Exchange 2010 server using PowerShell v2.0 when it is launched. The script had [&hellip;]","og_url":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/","og_site_name":"Bhargav&#039;s IT Playground","article_published_time":"2010-02-20T03:18:50+00:00","author":"Bhargav","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Bhargav","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/#article","isPartOf":{"@id":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/"},"author":{"name":"Bhargav","@id":"https:\/\/bhargavs.com\/#\/schema\/person\/28f6d8c9b29f3a879483d65fc2ab5e26"},"headline":"PowerShell Variables and scopes","datePublished":"2010-02-20T03:18:50+00:00","mainEntityOfPage":{"@id":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/"},"wordCount":372,"commentCount":0,"publisher":{"@id":"https:\/\/bhargavs.com\/#\/schema\/person\/28f6d8c9b29f3a879483d65fc2ab5e26"},"keywords":["PowerShell Variable Scope"],"articleSection":["Exchange 2010","PowerShell"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/","url":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/","name":"PowerShell Variables and scopes - Bhargav&#039;s IT Playground","isPartOf":{"@id":"https:\/\/bhargavs.com\/#website"},"datePublished":"2010-02-20T03:18:50+00:00","breadcrumb":{"@id":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/bhargavs.com\/"},{"@type":"ListItem","position":2,"name":"PowerShell Variables and scopes"}]},{"@type":"WebSite","@id":"https:\/\/bhargavs.com\/#website","url":"https:\/\/bhargavs.com\/","name":"Bhargav's IT Playground","description":"Passion for Technology. Power of Collaboration.","publisher":{"@id":"https:\/\/bhargavs.com\/#\/schema\/person\/28f6d8c9b29f3a879483d65fc2ab5e26"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/bhargavs.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/bhargavs.com\/#\/schema\/person\/28f6d8c9b29f3a879483d65fc2ab5e26","name":"Bhargav","logo":{"@id":"https:\/\/bhargavs.com\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/bhargavs.com"]}]}},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":97,"url":"https:\/\/bhargavs.com\/index.php\/2009\/06\/12\/check-exchange-2003-vitals-powershell-2\/","url_meta":{"origin":1643,"position":0},"title":"Check Exchange 2003 vitals with PowerShell","author":"Bhargav","date":"June 12, 2009","format":false,"excerpt":"I have written recently about Free System PTEs and \/PAE usage in Exchange 2003 mailbox servers. I set out to write a PowerShell script that will run against given list of servers and report back certain vitals including boot.ini settings, SystemPages registry setting and current performance data for Free Sytem\u2026","rel":"","context":"In &quot;Exchange 2003&quot;","block_context":{"text":"Exchange 2003","link":"https:\/\/bhargavs.com\/index.php\/category\/microsoft\/exchange-server\/exchange-2003\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1650,"url":"https:\/\/bhargavs.com\/index.php\/2010\/03\/29\/script-to-enable-preview-pane-for-powershell-scripts\/","url_meta":{"origin":1643,"position":1},"title":"Script to enable preview pane for PowerShell scripts","author":"Bhargav","date":"March 29, 2010","format":false,"excerpt":"If you are running Windows 7, you probably know what preview pane is. And if you use PowerShell and create ps1 scripts, you may also wonder how can you enable preview for PowerShell scripts in Windows Explorer. Well, Nate Bruneau shared how to edit registry to enable preview for ps1\u2026","rel":"","context":"In &quot;PowerShell&quot;","block_context":{"text":"PowerShell","link":"https:\/\/bhargavs.com\/index.php\/category\/microsoft\/powershell\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1627,"url":"https:\/\/bhargavs.com\/index.php\/2009\/06\/12\/check-exchange-2003-vitals-powershell\/","url_meta":{"origin":1643,"position":2},"title":"Check Exchange 2003 vitals with PowerShell \u2013 Part II","author":"Bhargav","date":"June 12, 2009","format":false,"excerpt":"In continuation to my previous post \u201cCheck Exchange 2003 vitals with PowerShell\u201d, I also have a code block that you can replace if you want to query all exchange servers in your environment dynamically with script instead of using text file as in the code I posted earlier. In the\u2026","rel":"","context":"In &quot;Exchange 2003&quot;","block_context":{"text":"Exchange 2003","link":"https:\/\/bhargavs.com\/index.php\/category\/microsoft\/exchange-server\/exchange-2003\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1679,"url":"https:\/\/bhargavs.com\/index.php\/2012\/05\/03\/exchange-management-shell-error-500-internal-server-error\/","url_meta":{"origin":1643,"position":3},"title":"Exchange Management Shell Error 500 &#8211; Internal Server Error","author":"Bhargav","date":"May 3, 2012","format":false,"excerpt":"I have come across this issue enough times that even if it is documented on TechNet it deserves mention here. When you launch Exchange Management Shell or try to connect to an Exchange 2010 Server remotely using PowerShell, you get error \u201c500 \u2013 Internal Server Error. There is a problem\u2026","rel":"","context":"In &quot;Exchange 2010&quot;","block_context":{"text":"Exchange 2010","link":"https:\/\/bhargavs.com\/index.php\/category\/microsoft\/exchange-server\/exchange-2010\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1203,"url":"https:\/\/bhargavs.com\/index.php\/2015\/12\/23\/how-to-find-net-framework-version-using-powershell\/","url_meta":{"origin":1643,"position":4},"title":"How to find .NET Framework version using PowerShell","author":"Bhargav","date":"December 23, 2015","format":false,"excerpt":"Often times when I am getting ready to install Exchange 2016 or Exchange 2013, I look at pre-requisites and wonder if correct version of .NET Framework is already installed on the server or not. It certainly saves me time if it is already installed and depending on status of latest\u2026","rel":"","context":"In &quot;PowerShell&quot;","block_context":{"text":"PowerShell","link":"https:\/\/bhargavs.com\/index.php\/category\/microsoft\/powershell\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1672,"url":"https:\/\/bhargavs.com\/index.php\/2011\/09\/27\/mythbusters-exchange-server-2010-and-powershell-remoting\/","url_meta":{"origin":1643,"position":5},"title":"Mythbusters\u2013Exchange Server 2010 and PowerShell Remoting","author":"Bhargav","date":"September 27, 2011","format":false,"excerpt":"A misconception that WinRM listener needs to be configured in order to be able to connect to Exchange Server 2010 had popped up a couple times in my conversations recently so I decided to clear the confusion. Guest blogging for my friends at IT Pro Africa, I have written the\u2026","rel":"","context":"In &quot;Exchange 2010&quot;","block_context":{"text":"Exchange 2010","link":"https:\/\/bhargavs.com\/index.php\/category\/microsoft\/exchange-server\/exchange-2010\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_shortlink":"https:\/\/wp.me\/pkROc-qv","_links":{"self":[{"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/posts\/1643","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/comments?post=1643"}],"version-history":[{"count":0,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/posts\/1643\/revisions"}],"wp:attachment":[{"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/media?parent=1643"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/categories?post=1643"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/tags?post=1643"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}