gpt4 book ai didi

powershell - 在 powershell 脚本中尝试/捕获 aws cli 错误

转载 作者:行者123 更新时间:2023-12-04 14:09:03 26 4
gpt4 key购买 nike

我正在尝试让脚本自动为项目创建 ECR 存储库作为管道的一部分。我想先检查它是否已经存在,但是 describe-repositories返回一个错误而不是“nothing”,并且它没有被 try/catch 捕获。

try{
$ErrorActionPreference = "Stop"
aws ecr describe-repositories --repository-names "some-project"
}
catch {
aws ecr create-repository --repository-name "some-project"
}
输出:
An error occurred (RepositoryNotFoundException) when calling the DescribeRepositories operation: The repository with name '...' does not exist in the registry with id '...'
有没有办法捕获错误?
编辑:设置 $ErrorActionPreference = "Stop"不会改变行为。

最佳答案

您应该可以利用 $LastExitCode 告诉发生了错误(一些 minimal AWS CLI documentation 对此)

aws ecr describe-repositories --repository-names "some-project"

if ($LastExitCode) {
aws ecr create-repository --repository-name "some-project"
}
如果您想要实际的错误消息,您应该能够利用 How to capture error messages thrown by a command? 中所述的重定向。

真的,尽管我认为您可以在此处进行其他两项改进:
  • list them 而不是描述特定的存储库看看你想要的是否存在:
  • $repositories = (aws ecr describe-repositories) | ConvertFrom-Json

    if ("some-project" -notin $repositories.repositories.repositoryName) {
    aws ecr create-repository --repository-name "some-project"
    }
  • 如果这是一个选项,请使用 AWS Tools for PowerShell ... 所以你可以使用 Get-ECRRepository以及诸如 $ErrorActionPreference 之类的东西工作。
  • 关于powershell - 在 powershell 脚本中尝试/捕获 aws cli 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66011408/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com