在同一PowerShell脚本中安装AWS CLI后调用aws命令报错求助
我用Packer创建AWS AMI镜像时,运行以下PowerShell脚本——先下载安装AWS CLI,之后马上调用它。我知道安装会更新Windows PATH,但当前脚本里没法立即生效,所以特意切换到CLI安装目录再执行命令:
$SETUP_DIR = "C:\Setup" New-Item -Path $SETUP_DIR -ItemType Directory -Force -ErrorAction SilentlyContinue Clear-Host Set-Location -Path $SETUP_DIR -PassThru # install AWS CLI msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi /quiet Write-Host "AWS CLI installation completed." # Set location to AWS CLI Set-Location -Path "C:\Program Files\Amazon\AWSCLIV2" -PassThru # Download utility from AWS S3 aws s3 cp s3://tools/utility.exe Write-Host "Utility download completed." # switch the location back to c:\setup Set-Location -Path $SETUP_DIR -PassThru
脚本执行时抛出错误The term 'aws' is not recognized,详情如下:
==> amazon-ebs.windows_server: aws s3 cp s3://tools/utility.exe ...
==> amazon-ebs.windows_server: + ~~~
==> amazon-ebs.windows_server: + CategoryInfo : ObjectNotFound: (aws:String) [], CommandNotFoundException
==> amazon-ebs.windows_server: + FullyQualifiedErrorId : CommandNotFoundException
==> amazon-ebs.windows_server:
amazon-ebs.windows_server:
==> amazon-ebs.windows_server: aws : The term 'aws' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the
==> amazon-ebs.windows_server: spelling of the name, or if a path was included, verify that the path is correct and try again.
解决办法
直接指定完整路径调用
不用切换目录,直接写全aws.exe的路径执行,同时注意s3 cp需要目标路径(示例中用.表示当前目录):& "C:\Program Files\Amazon\AWSCLIV2\aws.exe" s3 cp s3://tools/utility.exe .确保安装完成并刷新环境变量
msiexec的/quiet参数会直接返回,不会等安装完成就继续执行后续命令,导致CLI还没装好就被调用。改用Start-Process加-Wait等待安装结束,再手动刷新当前会话的PATH:# 安装AWS CLI并等待完成 Start-Process msiexec.exe -ArgumentList "/i https://awscli.amazonaws.com/AWSCLIV2.msi /quiet" -Wait Write-Host "AWS CLI installation completed." # 刷新当前会话的环境变量 $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") # 调用aws命令 aws s3 cp s3://tools/utility.exe .切换目录后加.\调用
PowerShell默认不会在当前目录查找可执行文件,即使切到安装目录,也要加.\指定当前路径:Set-Location -Path "C:\Program Files\Amazon\AWSCLIV2" -PassThru .\aws s3 cp s3://tools/utility.exe .
内容的提问来源于stack exchange,提问作者LP13

