Reputation: 11
I have a script that partially works it will install the app for chocolatey but the ELSE command seems to fail I'm new to scripting so possibly missing something here.
$localprograms1 = choco list --localonly
$program1 = "3cx"
If(Test-Path -Path "$env:ProgramData\Chocolatey")
{
if ($localprograms1 -like "*$program1*")
{
choco upgrade $program1
}
else
{
choco install $program1 -y
}
}
Else
{
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
{
if ($localprograms1 -like "*$program1*")
{
choco upgrade $program1
}
else
{
choco install $program1 -y
}
}
}
it seems to fail at the detection phase
Upvotes: 1
Views: 616
Reputation: 990
There are a few things I'd suggest
Just from a personal perspective, I would suggest re-ordering this to make it run more seamlessly (and to be a little less repetitive!).
param(
$Program = "3cx"
)
# First, make sure Chocolatey is available - if not, we install it!
if (-not (Get-Command choco -ErrorAction SilentlyContinue)) {
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
# Refresh the environment variables, to make sure choco is available
Import-Module $env:ProgramData\chocolatey\helpers\chocolateyProfile.psm1
Update-SessionEnvironment
}
# Having ensured Chocolatey is available, we can get our list of applications
# Using --limit-output (-r) and converting it from delimited format
$LocalPrograms = choco list --local-only --limit-output | ConvertFrom-Csv -Delimiter '|' -Header Name, Version
# We can now check if the package is present, and can install / upgrade if not
if ($Program -in $LocalPrograms.Name) {
choco upgrade $program1
} else {
choco install $program1 --confirm
}
Having said that, choco upgrade
will install or upgrade a program depending on it's presence, so you could replace everything after the installation of Chocolatey with choco upgrade $program1 --confirm
.
Upvotes: 2