{"id":1652,"date":"2010-07-07T13:04:34","date_gmt":"2010-07-07T21:04:34","guid":{"rendered":"http:\/\/www.bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/"},"modified":"2010-07-07T13:04:34","modified_gmt":"2010-07-07T21:04:34","slug":"deceiving-scopes-of-variables-in-a-function","status":"publish","type":"post","link":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/","title":{"rendered":"Deceiving scopes of variables in a function"},"content":{"rendered":"<p>I was recently troubleshooting a script when I came across a problem where a variable with defined scope was not retaining its value even though scope seemed correct. Let\u2019s look at simplified example below:<\/p>\n<pre class=\"brush: vb; smart-tabs: false;\">Function Global:Name-ofaFunction\n{\n$Global:VariableinQuestion = $null\n$VariableinQuestion = \"Value\"\n$VariableinQuestion\n}\n\nName-ofaFunction\n$VariableinQuestion\n<\/pre>\n<p>The function \u201cName-ofaFunction\u201d when called, creates a variable with global scope and sets its value to null. Next, it sets the value of a variable and prints current value to host. Part of the script, I am also calling variable after running the function. This helps me verify the value.<\/p>\n<p>When you run this script, however, you will notice that it prints current value (\u201cValue\u201d) of the variable only once.<\/p>\n<p>If you debug the code, you will notice that the variable is set to null when exiting the function! Interesting why that is happening when you have defined the variable scope to be global in line 3!!!<\/p>\n<p>So let\u2019s try this code.<\/p>\n<pre class=\"brush: vb; smart-tabs: false;\">Function Global:Name-ofaFunction\n{\n#$Global:VariableinQuestion = $null\n$global:VariableinQuestion = \"Value\"\n$VariableinQuestion\n}\n\nName-ofaFunction\n$VariableinQuestion\n<\/pre>\n<p>If you notice the difference, I have commented out line 3. Also, in line 4, I have added global scope to the variable. If you run this code, you will get the value of the variable printed to the host twice. Once inside the function and second time after the function!<\/p>\n<p>How did that happen? The code doesn\u2019t look much different. Only difference is where I define global scope. Why should that matter? Let me explain.<\/p>\n<p>Although I am not sure if it is a feature or a bug, it seems PowerShell is resetting variable scope to local in line 4 in first example. Because it resets the scope to local, the variable loses its value and is set to null when exiting the function. This is because the variable is created inside the function and is scoped as local for the function. This is fixed in second example by defining it as global right where I am setting its value.<\/p>\n<p>As you can imagine, there are many uses of setting correct scope of the variable. i.e. You may want to use the value returned by the function in another function. When you set the scope properly, the values are retained in appropriate scopes which can be used by other piece of code like functions of cmdlets run on host.<\/p>\n<p>For more information on scope, you can read my previous blog post \u201c<a href=\"http:\/\/www.bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/\">PowerShell Variables and Scopes<\/a>\u201d and TechNet article \u201c<a href=\"http:\/\/technet.microsoft.com\/en-us\/library\/dd315289.aspx\">about_Scopes<\/a>\u201d.<\/p>\n<p>Originally posted at http:\/\/blogs.technet.com\/bshukla<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I was recently troubleshooting a script when I came across a problem where a variable with defined scope was not retaining its value even though scope seemed correct. Let\u2019s look [&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":[19],"tags":[],"class_list":["post-1652","post","type-post","status-publish","format-standard","hentry","category-powershell"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.6 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Deceiving scopes of variables in a function - 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\/07\/07\/deceiving-scopes-of-variables-in-a-function\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Deceiving scopes of variables in a function - Bhargav&#039;s IT Playground\" \/>\n<meta property=\"og:description\" content=\"I was recently troubleshooting a script when I came across a problem where a variable with defined scope was not retaining its value even though scope seemed correct. Let\u2019s look [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/\" \/>\n<meta property=\"og:site_name\" content=\"Bhargav&#039;s IT Playground\" \/>\n<meta property=\"article:published_time\" content=\"2010-07-07T21:04:34+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\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/\"},\"author\":{\"name\":\"Bhargav\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#\\\/schema\\\/person\\\/28f6d8c9b29f3a879483d65fc2ab5e26\"},\"headline\":\"Deceiving scopes of variables in a function\",\"datePublished\":\"2010-07-07T21:04:34+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/\"},\"wordCount\":402,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#\\\/schema\\\/person\\\/28f6d8c9b29f3a879483d65fc2ab5e26\"},\"articleSection\":[\"PowerShell\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/\",\"url\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/\",\"name\":\"Deceiving scopes of variables in a function - Bhargav&#039;s IT Playground\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/#website\"},\"datePublished\":\"2010-07-07T21:04:34+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/bhargavs.com\\\/index.php\\\/2010\\\/07\\\/07\\\/deceiving-scopes-of-variables-in-a-function\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/bhargavs.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Deceiving scopes of variables in a function\"}]},{\"@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":"Deceiving scopes of variables in a function - 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\/07\/07\/deceiving-scopes-of-variables-in-a-function\/","og_locale":"en_US","og_type":"article","og_title":"Deceiving scopes of variables in a function - Bhargav&#039;s IT Playground","og_description":"I was recently troubleshooting a script when I came across a problem where a variable with defined scope was not retaining its value even though scope seemed correct. Let\u2019s look [&hellip;]","og_url":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/","og_site_name":"Bhargav&#039;s IT Playground","article_published_time":"2010-07-07T21:04:34+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\/07\/07\/deceiving-scopes-of-variables-in-a-function\/#article","isPartOf":{"@id":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/"},"author":{"name":"Bhargav","@id":"https:\/\/bhargavs.com\/#\/schema\/person\/28f6d8c9b29f3a879483d65fc2ab5e26"},"headline":"Deceiving scopes of variables in a function","datePublished":"2010-07-07T21:04:34+00:00","mainEntityOfPage":{"@id":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/"},"wordCount":402,"commentCount":0,"publisher":{"@id":"https:\/\/bhargavs.com\/#\/schema\/person\/28f6d8c9b29f3a879483d65fc2ab5e26"},"articleSection":["PowerShell"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/","url":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/","name":"Deceiving scopes of variables in a function - Bhargav&#039;s IT Playground","isPartOf":{"@id":"https:\/\/bhargavs.com\/#website"},"datePublished":"2010-07-07T21:04:34+00:00","breadcrumb":{"@id":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/bhargavs.com\/index.php\/2010\/07\/07\/deceiving-scopes-of-variables-in-a-function\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/bhargavs.com\/"},{"@type":"ListItem","position":2,"name":"Deceiving scopes of variables in a function"}]},{"@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":1643,"url":"https:\/\/bhargavs.com\/index.php\/2010\/02\/19\/powershell-variables-and-scopes\/","url_meta":{"origin":1652,"position":0},"title":"PowerShell Variables and scopes","author":"Bhargav","date":"February 19, 2010","format":false,"excerpt":"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 a function which is called upon when profile is loaded. The function looked like the following: function connect-remotely() { if\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":1648,"url":"https:\/\/bhargavs.com\/index.php\/2010\/03\/25\/script-to-suppress-link-state-updates\/","url_meta":{"origin":1652,"position":1},"title":"Script to suppress Link State Updates","author":"Bhargav","date":"March 25, 2010","format":false,"excerpt":"If you are in process of upgrading from Exchange 2003 to Exchange 2010, you must have read \u201cUpgrade from Exchange 2003 Transport\u201d article on Technet which spells out the details of a requirement - \u201cminor link state updates must be suppressed to make sure that message looping doesn't occur when\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":97,"url":"https:\/\/bhargavs.com\/index.php\/2009\/06\/12\/check-exchange-2003-vitals-powershell-2\/","url_meta":{"origin":1652,"position":2},"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":1652,"position":3},"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":1649,"url":"https:\/\/bhargavs.com\/index.php\/2010\/05\/19\/script-to-configure-static-ports-on-exchange-server-2010\/","url_meta":{"origin":1652,"position":4},"title":"Script to configure static ports on Exchange Server 2010","author":"Bhargav","date":"May 19, 2010","format":false,"excerpt":"This post is depricated. Please use newer version of script and read more details here: http:\/\/www.bhargavs.com\/index.php\/2011\/10\/21\/script-to-configure-static-ports-on-exchange-server-2010-2\/ If you are planning to implement or are implementing Exchange Server 2010, you may have already noticed that with new changes introduced in this version we highly recommend that you load balance your CAS\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":34526,"url":"https:\/\/bhargavs.com\/index.php\/2024\/01\/30\/clearing-microsoft-teams-cache-with-powershell\/","url_meta":{"origin":1652,"position":5},"title":"Clearing Microsoft Teams Cache with PowerShell","author":"Bhargav","date":"January 30, 2024","format":false,"excerpt":"Introduction I recently came across a need to clear Teams cache. While the task might be simple, I ended up spending a little more time to address the scenarios I can foresee so the PowerShell script is more useful that a single use case. In this blog post, we'll be\u2026","rel":"","context":"In &quot;General&quot;","block_context":{"text":"General","link":"https:\/\/bhargavs.com\/index.php\/category\/general\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_shortlink":"https:\/\/wp.me\/pkROc-qE","_links":{"self":[{"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/posts\/1652","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=1652"}],"version-history":[{"count":0,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/posts\/1652\/revisions"}],"wp:attachment":[{"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/media?parent=1652"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/categories?post=1652"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bhargavs.com\/index.php\/wp-json\/wp\/v2\/tags?post=1652"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}