I am new to powershell here. I can't figure out why after successfully installing AWS CLI, I intermittently get back aws
command not recognized error. I put in sleep thinking some environment variables might be getting set in background. Need help figuring out what do I need to do here to able to to successfully execute $putItem command.
I followed the instructions here https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-windows.html
PLEASE NOTE: The whole thing has to be automated, so I can't manually login to a host and fix something as this same script has to be run on 100 hosts
Write-Output "Checking if AWS CLI support exists..."
cmd.exe /c "aws --version"
if ($LASTEXITCODE -eq 0){
Write-Output "AWS CLI installed already"
} else {
Write-Output "Installing AWS CLI V2"
cmd.exe /c "msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi /qn"
if ($LASTEXITCODE -eq 0){
Write-Output "AWS CLI installed successfully"
Start-Sleep -s 5
} else {
Write-Output "Could not install AWS CLI"
exit 1
}
}
$putItem = 'aws dynamodb put-item --table-name ' $instanceStatusDDBTable ' --item "{\"HostName\" : {\"S\" : \"' $instanceName '\"}, \"Modules\" : {\"M\" : {}}, \"DAGName\" : {\"S\" : \"' $dagName '\"}}"'
Write-Output "Executing DB put item query $putItem"
cmd.exe /c $putItem
if ($LASTEXITCODE -eq 0){
Write-Output "Created entry for $instanceName in $instanceStatusDDBTable DDB table"
} else {
Write-Output "Could not complete put Item operation for $instanceName"
exit 1
}
Here is the output
Checking if AWS CLI support exists...
Installing AWS CLI V2
AWS CLI installed successfully
Executing DB put item query aws dynamodb put-item --table-name Ex2019-HostStatusTable --item "{\"HostName\" : {\"S\" : \"Host1\"}, \"Modules\" : {\"M\" : {}}, \"DAGName\" : {\"S\" : \"USW-D01\"}}"
Could not complete put Item operation for Host1
Error output -
'aws' is not recognized as an internal or external command,
operable program or batch file.
CodePudding user response:
Try adding the below code to refresh your environment variables after you check your $LASTEXITCODE variable. The shell session has to regather the updated environment variables your installer just added. See this response for more info.
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") ";" [System.Environment]::GetEnvironmentVariable("Path","User")
You may also want to consider using the Start-Process with the -wait
and -passthru
params to invoke your installer as the cmd may not wait long enough for the app to finish installing. You can read up on here. I do agree with David, you could just check to see if it's installed by running aws --version
and then reading in the version number or catching the error in a try catch block.