windows - 如果不满足条件,如何退出巧克力安装?

标签 windows powershell chocolatey

在我常用的 PowerShell 脚本中,像往常一样,我在执行正常完整性检查时使用 Exit 1 退出脚本,因此如果不满足条件,我提前退出并通知用户满足条件。

Chocolatey 包开发是否遵循相同的 PoSh 方式?或者是否有任何Chocolatey 方式,例如helperscore-extension 可以为开发人员做到这一点?例如:

我希望用户为我的 SQL Server 巧克力包提供 SQL Server iso 路径 --params "/IsoPath:C:\Pkg",如果没有提供路径,包安装应该会失败:

$pp = Get-PackageParameters
if (!pp['IsoPath']) {
   Write-Host "No 'ISO' path is provided, please provide path in '--params'"
   Exit 1
}

上面的代码片段是否会导致安装失败,或者有什么巧妙的方法可以做到这一点?

最佳答案

有几种方法可以做到这一点。

第一种是简单地抛出异常。 vcredist140 就是一个很好的例子包,它决定这个包是否打算在当前安装它的操作系统上使用。

$os = Get-WmiObject -Class Win32_OperatingSystem
$version = [Version]$os.Version
if ($version -ge [Version]'6.1' -and $version -lt [Version]'6.2' -and 
$os.ServicePackMajorVersion -lt 1)
{
  # On Windows 7 / Server 2008 R2, Service Pack 1 is required.
  throw 'This package requires Service Pack 1 to be installed first. The 
"KB976932" package may be used to install it.'
}
elseif ($version -ge [Version]'6.0' -and $version -lt [Version]'6.1' -and 
$os.ServicePackMajorVersion -lt 2)
{
  # On Windows Vista / Server 2008, Service Pack 2 is required.
  throw 'This package requires Service Pack 2 to be installed first.'
}
elseif ($version -ge [Version]'5.2' -and $version -lt [Version]'6.0' -and 
$os.ServicePackMajorVersion -lt 2)
{
  # On Windows Server 2003 / XP x64, Service Pack 2 is required.
  throw 'This package requires Service Pack 2 to be installed first.'
}
elseif ($version -ge [Version]'5.1' -and $version -lt [Version]'5.2' -and 
$os.ServicePackMajorVersion -lt 3)
{
  # On Windows XP, Service Pack 3 is required.
  throw 'This package requires Service Pack 3 to be installed first.'
}

另一种方法是使用 Chocolatey 提供的 Set-PowerShellExitCode 辅助方法:

https://chocolatey.org/docs/helpers-set-power-shell-exit-code

如果您需要专门将退出代码设置为稍后使用的内容。

关于windows - 如果不满足条件,如何退出巧克力安装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247318/

相关文章:

powershell - 如何在Powershell上运行长时间运行的程序的远程程序

使用 Get-ChildItem 存储到数组时,Powershell Item-Property 未展开

chocolatey - 如何使用 Chocolatey 安装 DotNet4.0?

elasticsearch - 如何在AppVeyor构建代理上可靠地安装和运行Elasticsearch?

windows - mysqldump 是否返回我可以在批处理文件中使用的错误代码?

python - 在 PyInstaller 中,为什么 NumPy.Random.Common 不能作为模块加载?

c - Lua c lib Windows : The specified procedure could not be found

windows - 从文件中的偏移量加载库

Powershell 哈希表检索问题

xml - 为PowerShell脚本异常的结果添加颜色