header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

Scope problem...
Last Post 22 Jul 2008 01:54 AM by glnsize. 2 Replies.
Printer Friendly
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
darthchocoboUser is Offline
New Member
New Member
Posts:2
Avatar

--
21 Jul 2008 06:01 PM  

Ok so i have this very simple script. Now When i execute this script it should be all "Hello" becuase of the dot sourcing right? But when i execute it it goes Hello Hello Good Bye Good Bye as if it is making the scope of the script the scope of the function not the other way around. Thank you for your time and help,

 

 

 

 

$var1 = "Hello"
   
        Function TheFunction{
            Write-Host $var1
            $var1 = "GoodBye"
            Write-Host $var1
            }
            Write-Host $var1
            . TheFunction
            Write-Host $var1
   

EBGreenUser is Online
New Member
New Member
Posts:64
Avatar

--
21 Jul 2008 07:12 PM  
Dot sourcing executes in the current scope. Try using & and see if you get the result that you expected. Check this for more info:

http://www.captainliteral.net/2007/01/29/powershell-basics-%E2%80%93-running-scripts/
glnsizeUser is Online
Basic Member
Basic Member
Posts:101

--
22 Jul 2008 01:54 AM  

Yikes, 1100 word read... little overkill...

darthchocobo,

You are correct you ran into a scope problem.  Posh, however behaved it self...
Focus in on the TheFunction portion of your script.  When you dot source anything in powershell it executes it into your current scope.  therefor...

 

function TheFunction{
Write-Host $var1
$var1 = "GoodBye"
Write-Host $var1
}
write-Host $var1
##### the culprit #####
. TheFunction
Write-Host $var1

By dot sourcing your function it is the same as doing the following...

 

write-Host $var1
Write-Host $var1 # This is
$var1 = "GoodBye" # Your Function
Write-Host $var1 # Running
Write-Host $var1

 

In effect the code contained within the function is copied into your current session and then executed.  So when do you use '&'?  Poshoholic did a fantastic job expaining that little bugger the other day scroll all the way down...

since your calling a function without any wild conditions just call it... posh know's what your trying to do here...

 

$var1 = "Hello"
function TheFunction {
Write-Host $var1
$var1 = "GoodBye"
Write-Host $var1
}

write-Host $var1
TheFunction
Write-Host $var1

 

Scoping still kicks me in the teeth some times. No such problem with vbscript ;) still getting used to it all... ~Glenn

BTW, having to edit this three times to get the code tags to work properly is a pain. 

You are not authorized to post a reply.

Active Forums 4.1
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer