0

I've written a function that "wraps" around Install-Module meaning it does all the PackageProvider and PSRepository work before installing a Module:

Function Install-ModuleWrapper {

    #Requires -RunAsAdministrator

    Param(
        [string]$ModuleName,
        [switch]$CheckIfInstalled
    )

    if ($CheckIfInstalled.IsPresent)
    {
        if (Get-Module -ListAvailable -Name $ModuleName) { Throw "Module is installed" }
    }

    # Sicherstellen, dass NuGet Provider Installiert ist
    $NuGet = (Get-PackageProvider | Select-Object -ExpandProperty Name) -contains "NuGet"
    if (!$NuGet) { Install-PackageProvider NuGet -Force > $null }

    # Sicherstellen, dass PSGallery vertraut wird
    Set-PSRepository PSGallery -InstallationPolicy Trusted

    # Modul installieren
    Install-Module $ModuleName

}

I will use this function in a script like so:

Write-Host "Start"
. '\\server\share\Install-ModuleWrapper.ps1'
Install-ModuleWrapper PSWindowsUpdate -CheckIfInstalled
Write-Host "I print stuff to stdout"
Do-MoreStuff

As you can see in the function, I want to stop the function if a module is already installed.

Howeverm if I use Throw inside Install-ModuleWrapper, the code after the function is never executed.

Can I "soft-terminate" a script or a function somehow, so that the other stuff after the function is still executed?

As I am writing this I realize I can simply use if() {} else {} as a workaround for this function, however I'm still interested in how to "soft-terminate" a function if I need to.

1
  • 1
    If you throw an exception, you're telling PowerShell something terrible has happened that needs dealt with and PowerShell halts execution and starts looking for some code to handle it. Since you have none, it falls back on it's default behaviour (output some error details) and doesn't return to execute the rest of your code. You can manage this process yourself by using try/catch Commented Oct 30, 2019 at 9:00

1 Answer 1

3

I'd just do it this way:

Function Install-ModuleWrapper {

    #Requires -RunAsAdministrator

    Param(
        [string]$ModuleName,
        [switch]$CheckIfInstalled
    )

    if ($CheckIfInstalled.IsPresent)
    {
        if (Get-Module -ListAvailable -Name $ModuleName) { Return "Module is installed" }
    }

    # Sicherstellen, dass NuGet Provider Installiert ist
    Write-Host "Installing stuff"

}

For better control though maybe use Try...Catch?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.