Scope Lab 5.6 in Month of Lunches

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 2 years, 1 month ago.

  • Author
    Posts
  • #19450
    Profile photo of TJ Anon
    TJ Anon
    Participant

    I have several questions about Lab 5.6 in Learning Powershell in a Month of Lunches. The book gives a function that doesn't work because of a scope issue. The solution that is given to solve it, is to make the scope global when creating the PSDrives. Yet, in the chapter, it says "We get particularly irritated when we see people writing scripts that dump things into some $global:variable in order to pass information from one function to another." Seems to be contradictory.

    Also, twice now, I've noticed that the book says when the function ends, the variables are no longer available. That is not true on my system. In the lab that we're discussing, for instance, I can access the Appdata: and Temp: drives. Wondering what's different about my system that I can access the drives after the script ends.

  • #19451
    Profile photo of TJ Anon
    TJ Anon
    Participant

    Instead of renaming the ps1, I just copied the code from the book (that we're supposed to fix in the lab). It's below.

    Function New-Drives {
    
    Param()
    
    New-PSDrive -Name AppData -PSProvider FileSystem -Root $env:Appdata 
    New-PSDrive -Name Temp -PSProvider FileSystem -Root $env:TEMP 
    
    $mydocs=Join-Path -Path $env:userprofile -ChildPath Documents
    New-PSDrive -Name Docs -PSProvider FileSystem -Root $mydocs
    
    }
    
    New-Drives
    DIR temp: | measure-object –property length -sum
    
  • #19453
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Hi TJ,

    PSDrives and Variables are two different things. PSDrives are essentially always global. I don't have the book in front of me to know what you're referring to when you say "The book gives a function that doesn't work because of a scope issue. The solution that is given to solve it, is to make the scope global when creating the PSDrives", and the attachment would need to be renamed from .ps1 to .txt.

You must be logged in to reply to this topic.