0

I would like to know the scope of the variable $crazy in the following PowerShell script:

function Test1 { 
    Write-Host $crazy 
}  

function Main { 
    $crazy = Read-Host "Type anything" 
    Test1 
} 

Main 

I was expecting $crazy to be only visible within Main function but, to my surprise, the function Test1 was able to access it. I can guarantee that there's no previously declared $crazy variable in my PS session.

I'll be honest I didn't fully understand about_scope so I used ISE to debug through the script and tested the scope of the variable with the following pattern $<scope>:$crazy and the variable didn't even appear every scope I've used.

1
  • 2
    $crazy is local to function Main{...}, and can only be seen/read from Test1 because you call it from inside Main Commented Feb 6, 2017 at 14:32

1 Answer 1

2

In this case $crazy is scoped to the Main function, so it is available inside of Main and as such available to any function that is called by Main. If you were to attempt to call $crazy from outside of Main you'd find that it was not yet set. Does that help?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.