Powershell get region from AWS metadata

You can use ConvertFrom-Json :

PS C:\> $region = (Invoke-WebRequest -UseBasicParsing -Uri http://169.254.169.254/latest/dynamic/instance-identity/document | ConvertFrom-Json | Select region).region

edit: added -UseBasicParsing


Will this work?

PS C:\> $region = invoke-restmethod -uri http://169.254.169.254/latest/meta-data/placement/availability-zone

PS C:\> $region.Substring(0,$region.Length-1)

Parsing the availability-zone is not the safest way. Region name is available as an attribute of the Instance Identity Document, which is generated when the instance is launched. There are two options to read this information with Powershell:

You could use Invoke-WebRequest:

IWR (also aliased as curl and wget) works fine, but it can only deal with HTML. So you need an extra step to parse JSON. It uses the IE COM interface to parse the DOM by default, but you can avoid that with the -UseBasicParsing option.

PS C:\> curl http://169.254.169.254/latest/dynamic/instance-identity/document | ConvertFrom-Json | Select region

region
------
us-east-1

PS C:\> (curl http://169.254.169.254/latest/dynamic/instance-identity/document | ConvertFrom-Json).region
us-east-1

But Invoke-RestMethod is the best option:

Since this is a REST interface, IRM is the best choice because it natively supports JSON and XML.

PS C:\> irm http://169.254.169.254/latest/dynamic/instance-identity/document | Select region

region
------
us-east-1

PS C:\> (irm http://169.254.169.254/latest/dynamic/instance-identity/document).region
us-east-1

PS C:\> irm http://169.254.169.254/latest/dynamic/instance-identity/document | % region
us-east-1