【问题标题】:Powershell script to install app via choclatey but also check for choclatey is installed if not then it will install itPowershell脚本通过chocolatey安装应用程序,但如果没有安装,还检查chocolatey是否安装它会安装它
【发布时间】:2022-10-13 19:12:50
【问题描述】:

我有一个部分工作的脚本,它将为巧克力安装应用程序,但 ELSE 命令似乎失败了我是脚本新手,所以可能在这里遗漏了一些东西。

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

它似乎在检测阶段失败了

【问题讨论】:

  • 我已经给出了一个应该可以工作的脚本(例如,确保 Chocolatey 在所有场景中运行之前都可用),但是如果您提供运行脚本时遇到的错误,人们将能够更轻松地提供帮助。

标签: scripting chocolatey


【解决方案1】:

我有几点建议

仅从个人角度来看,我建议重新排序以使其运行更加无缝(并且减少重复性!)。

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:ProgramDatachocolateyhelperschocolateyProfile.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
}

话虽如此,choco upgrade 将根据程序的存在来安装或升级程序,因此您可以在安装 Chocolatey 后将所有内容替换为choco upgrade $program1 --confirm

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多