AWS Powershell to retrieve AWS account number AWS Powershell to retrieve AWS account number powershell powershell

AWS Powershell to retrieve AWS account number


Not directly. However, your Account ID is a part of the Arn of resources that you create... and those that are automatically created for you. Some resources will also list you as an OwnerId.

The Default Security Group is automatically created for you in each region, and cannot be deleted. This makes it a reliable candidate for retrieving our account Id.

Example:

PS C:/> $accountId = @(get-ec2securitygroup -GroupNames "default")[0].OwnerIdPS C:/> $accountId000011112222


Nice and simple

(Get-STSCallerIdentity).Account

...or

(Get-STSCallerIdentity -Region [your_aws_region]).Account


I was unable to comment on the other provided answer, so I'll have to offer my own solution as a slight modification.

I do believe the OwnerId on all groups will be the Account Id. However you may not have a "default" group. I recommend leaving out the -GroupNames "default". Also, I'm showing my example using a SAML token, as that is our case coming in with AD authorization.

$awsAccountNumber = (get-ec2securitygroup -ProfileName saml -Region us-west-2)[0].OwnerId

Hopefully that will be of some use.