reading file

Tagged: 

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Tony Antony Tony Antony 4 months, 3 weeks ago.

  • Author
    Posts
  • #61120
    Profile photo of Tony Antony
    Tony Antony
    Participant

    I have the following test function that reads content of $INI

    $INI = '\\hqfs1\users\tantony\PowerShell\CalenderGroup\config.ini'
    
    function test
    {
        $Read_INI = Get-Content $INI
    }
    
    test

    But, when I call it in line 8, it doesn't display the content. What am I doing wrong?

  • #61123
    Profile photo of Don Jones
    Don Jones
    Keymaster

    You've put the content into $Read_INI. You haven't done anything with $Read_INI to make it display anyplace.

    Additionally, you're engaging in a poor practice. You've defined $INI outside the function, but are using it inside the function. That's crossing scopes, and it's going to land you in a debugging hell one day. Functions should accept their input via parameters, not rely on external variables. Consider reading "Learn PowerShell Toolmaking in a Month of Lunches" if you're interested in building functions; it'll get you on the right path!

  • #61125
    Profile photo of Tony Antony
    Tony Antony
    Participant

    Thank you,
    how would I make $INI "public" so that it's defined anywhere? How would I fix it so that when I call test as in line 8, it would show the content of $INI?

    The reason I have $INI outside function is because I'll be using that variable more than once.

    Thank you, I will look at the ebook also.

  • #61126
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Well, it's a book-book, not necessarily an ebook, and it does answer all those questions. Very briefly, though, you don't WANT functions using "public" variables. That's the bad practice.

    $INI = '\\hqfs1\users\tantony\PowerShell\CalenderGroup\config.ini'
    
    function test
    {
        param([string]$ini_path)
        $Read_INI = Get-Content $ini_path
        Write-Output $Read_INI
    }
    
    test -ini_path $INI
    

    Would be more correct. I've also emitted the contents to the output pipeline, so the content will now display as the result of your function. Anything written to Output by your function is your function's actual output.

    I'm massively glossing over a lot of important detail here, so I _do_ recommend reading the book, or something similar, so that you understand what and why is happening. And if you're not familiar with what commands like Get-Content are doing, you might even want to start with "Learn Windows PowerShell in a Month of Lunches." For example, if you're not aware that $Read_INI contains a collection of System.String objects, and not just a giant block of text, then you'll want to begin at the beginning with that book.

  • #61131
    Profile photo of Tony Antony
    Tony Antony
    Participant

    Thank you

You must be logged in to reply to this topic.