Problems with Lesson 1 for Powershell

Patricia Curry 0 Reputation points
2024-09-17T18:45:12.4+00:00

I have gone through the first lessons several times PI changes to 3 as opposed to 3.14. I don't know what I am doing wrong.

This question is related to the following Learning Module

Azure Training
Azure Training
Azure: A cloud computing platform and infrastructure for building, deploying and managing applications and services through a worldwide network of Microsoft-managed datacenters.Training: Instruction to develop new skills.
1,524 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 53,896 Reputation points
    2024-09-17T19:46:02.8266667+00:00

    In step 1 you define a local variable called $PI with the value 3.14.

    In steps 2 and 3 you create a new .ps1 file and then put code in that script file to assign the value 3.14 to $PI and then displays the value of $PI. Since the file defines a new variable, with the same name, and then displays it the output will show the value of the variable as defined by the script.

    In step 4 you run the script.

    Finally in step 5 you show that the value of $PI is still 3.14.

    This behavior is defined in PowerShell under the Scopes documentation. Here's the high level important points made in the docs.

    • When you start a PS session then a new scope is created
    • When you run a script file then it creates a new child scope for that file
    • By default a child scope has access to the parent scope
    • Child scopes can run script files that create their own child scopes
    • When you reference a variable it'll start in the current scope and walk its way back to the parent scope if it isn't found at which point it'll create it

    Here's the general summary based upon the code you wrote.

    • You declare a variable called $PI in the parent scope
    • You run a file script
      • The file gets a new child scope
      • The script has access to $PI from the parent scope
      • The script creates its own $PI variable in the child scope and changes the value
      • Whenever the script references $PI it is now using its child scope version of that
      • When the script file ends then the child scope's $PI variable goes away
    • The parent scope's $PI is now accessible again

    You can sort of see this behavior by printing out the $PI variable in the file BEFORE you change the value.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.