Confused about function

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

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #41765
    Profile photo of Jeremy Bossard
    Jeremy Bossard
    Participant

    Hi,
    i'm still in the learning wagon about Powershell / scripting and i'm struggling with Function atm...

    this is about Installing programm via Powershell with startup Script (Windows server/gpo)

    With a "simple" software i do not have the need to use function, and the script work fine.
    But with more "complicate" software i sometimes have to install 6-7 ".exe" to make the software usable, that's why i thought about function...

    Base idea was like this :

    Function set-IsInstalled 
    {
          $IsInstalled=0    
          doregistrycheck, depending on result $IsInstalled=0, 1 or 2
    }
    
    function Set-Switch
    {
        switch ($IsInstalled) 
        {
            '0' {
                    Start-process $PathExe
                }
            '1' {
                    Start-process $UninstallString
                    Start-process $PathExe
                }
            '2' {
                   It's Installed
                }
        }
    }
    
    function InstallExe1
    {
        $PathExe="\\server\ExeFolder\Setup1.exe"
        Set-IsInstalled
        Get-Switch
    }
    
    function InstallExe2
    {
        $PathExe="\\server\ExeFolder\Setup2.exe"
        Set-IsInstalled
        Set-Switch
    }
    InstallExe1
    InstallExe2
    

    but ... it just doesn't work :-/
    I get i'm not using the Function properly, could you guide me on "how to do it right" ?

    #41769
    Profile photo of Dan Potter
    Dan Potter
    Participant

    The variables are out of scope. As written they will not carry over to other functions. I recommend using one function but to demonstrate...

    Function set-IsInstalled
    {
    $global:IsInstalled=0

    }

    function Set-Switch
    {
    switch ($IsInstalled)
    {
    '0' {
    write-host 'yes'
    }
    '1' {
    write-host 'no'
    }

    }
    }

    #41790
    Profile photo of Jack Neff
    Jack Neff
    Participant

    Dan's right your problem is variable scope. You can learn more about it by running "Get-Help about_scopes" in a powershell. You may need to run Update-Help first if it doesn't find it. Or go here.

    #41794
    Profile photo of Jeremy Bossard
    Jeremy Bossard
    Participant

    Hi,

    and thank you for your answer, to be honest i didn't have the time yet to check it but scope does make sense -_-'

    i'll come back to you if i got any issue with the reading 😉

    #41796
    Profile photo of Jack Neff
    Jack Neff
    Participant

    Please do we'd be glad to help. Good luck!

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.