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

标签 powershell aws-cli

我正在尝试让脚本自动为项目创建 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/

    相关文章:

    aws-lambda - 使用 Docker 支持的 AWS Lambda 时,如何通过 CLI 实现 "deploy new image"?

    windows - Powershell - 捕获套接字和进程

    c++ - 如何以编程方式关闭 Windows 中打开的文件/应用程序?

    regex - Powershell中的RegEx用下划线替换XML元素名称中的空格

    amazon-web-services - 通过 AWS CLI 查找 Beanstalk VPC-ID

    python - awscli 工具由 pip 安装并在 pip 中显示,但在访问时 - 找不到命令

    amazon-web-services - 调用 UploadServerCertificate 操作时出现客户端错误(SignatureDoesNotMatch)

    amazon-web-services - 为什么我没有获得有关我的 AWS IAM 身份的详细信息?未知输出类型 : JSON

    c# - 是否可以使用构建宏在 powershell 中设置 OutputPath?

    windows - 使用 Windows Control-C 剪贴板复制时如何保留制表符 `n` n?