Author Posts

June 5, 2016 at 11:30 am

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" ?

June 5, 2016 at 12:38 pm

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'
}

}
}

June 5, 2016 at 5:49 pm

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.

June 5, 2016 at 6:36 pm

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 😉

June 5, 2016 at 6:45 pm

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