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.
throwan 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