

Version 5 (V5) of the AWS Tools for PowerShell has been released\$1

For information about breaking changes and migrating your applications, see the [migration topic](https://docs.aws.amazon.com/powershell/v5/userguide/migrating-v5.html).

 [https://docs.aws.amazon.com/powershell/v5/userguide/migrating-v5.html](https://docs.aws.amazon.com/powershell/v5/userguide/migrating-v5.html)

# Configuring and using the AWS Tools for PowerShell
<a name="pstools-getting-started"></a>

Some of the topics in this section describe the fundamentals of using the Tools for Windows PowerShell after you have [installed the tools and set up authentication](pstools-getting-set-up.md). For example, they explain how to specify which [AWS Region](pstools-installing-specifying-region.md) the Tools for PowerShell should use when interacting with AWS.

Other topics in this section provide information about advanced ways that you can configure the tools, your environment, and your projects.

**Topics**
+ [AWS Region](pstools-installing-specifying-region.md)
+ [

# Credential and profile resolution
](creds-assign.md)
+ [Configure federated identity](saml-pst.md)
+ [

# Observability
](observability.md)
+ [

# Cmdlet discovery and aliases
](pstools-discovery-aliases.md)
+ [Pipelining, output, and iteration](pstools-pipelines.md)
+ [Users and roles](pstools-users-roles.md)
+ [

# Using legacy credentials
](pstools-cred-legacy.md)

# Specify the AWS Region for the AWS Tools for PowerShell
<a name="pstools-installing-specifying-region"></a>

There are two ways to specify the AWS Region to use when running AWS Tools for PowerShell commands:
+ Use the `-Region` common parameter on individual commands.
+ Use the `Set-DefaultAWSRegion` command to set a default Region for all commands.

Many AWS cmdlets fail if the Tools for Windows PowerShell can't figure out what Region to use. Exceptions include cmdlets for [Amazon S3](pstools-s3.md), Amazon SES, and AWS Identity and Access Management, which automatically default to a global endpoint.

 **To specify the region for a single AWS command** 

Add the `-Region` parameter to your command, such as the following.

```
PS > Get-EC2Image -Region us-west-2
```

 **To set a default region for all AWS CLI commands in the current session** 

From the PowerShell command prompt, type the following command.

```
PS > Set-DefaultAWSRegion -Region us-west-2
```

**Note**  
This setting persists only for the current session. To apply the setting to all of your PowerShell sessions, add this command to your PowerShell profile as you did for the `Import-Module` command.

 **To view the current default region for all AWS CLI commands** 

From the PowerShell command prompt, type the following command.

```
PS > Get-DefaultAWSRegion

Region    Name             IsShellDefault
------    ----             --------------
us-west-2 US West (Oregon) True
```

 **To clear the current default Region for all AWS CLI commands** 

From the PowerShell command prompt, type the following command.

```
PS > Clear-DefaultAWSRegion
```

 **To view a list of all available AWS Regions** 

From the PowerShell command prompt, type the following command. The third column in the sample output identifies which Region is the default for your current session.

```
PS > Get-AWSRegion

Region         Name                      IsShellDefault
------         ----                      --------------
ap-east-1      Asia Pacific (Hong Kong)  False
ap-northeast-1 Asia Pacific (Tokyo)      False
...
us-east-2      US East (Ohio)            False
us-west-1      US West (N. California)   False
us-west-2      US West (Oregon)          True
...
```

**Note**  
Some Regions might be supported but not included in the output of the `Get-AWSRegion` cmdlet. For example, this is sometimes true of Regions that are not yet global. If you're not able to specify a Region by adding the `-Region` parameter to a command, try specifying the Region in a custom endpoint instead, as shown in the following section.

## Specifying a Custom or Nonstandard Endpoint
<a name="specifying-a-custom-or-nonstandard-endpoint"></a>

Specify a custom endpoint as a URL by adding the `-EndpointUrl` common parameter to your Tools for Windows PowerShell command, in the following sample format.

```
PS > Some-AWS-PowerShellCmdlet -EndpointUrl "custom endpoint URL" -Other -Parameters
```

The following is an example using the `Get-EC2Instance` cmdlet. The custom endpoint is in the `us-west-2`, or US West (Oregon) Region in this example, but you can use any other supported AWS Region, including regions that are not enumerated by `Get-AWSRegion`.

```
PS > Get-EC2Instance -EndpointUrl "https://service-custom-url.us-west-2.amazonaws.com" -InstanceID "i-0555a30a2000000e1"
```

## Additional information
<a name="region-additional-info"></a>

For additional information about AWS Regions, see [AWS Region](https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html) in the *AWS SDKs and Tools Reference Guide*.

# Credential and profile resolution
<a name="creds-assign"></a>

## Credentials Search Order
<a name="cred-provider-chain-main"></a>

When you run a command, AWS Tools for PowerShell searches for credentials in the following order. It stops when it finds usable credentials.

1. Literal credentials that are embedded as parameters in the command line.

   We strongly recommend using profiles instead of putting literal credentials in your command lines.

1. Credentials specified by the `-Credential` parameter.

1. A profile name or profile location that was specified by using the [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html) cmdlet.
   + If you specify only a profile name, the command looks for the specified profile in the AWS SDK store and, if that does not exist, the specified profile from the AWS shared credentials file in the default location.
   + If you specify only a profile location, the command looks for the `default` profile from that credentials file.
   + If you specify both a name and a location, the command looks for the specified profile in that credentials file.

   If the specified profile or location is not found, the command throws an exception. Search proceeds to the following steps only if you did not specify a profile or location.

1. Credentials that are created from the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables, if all three variables have a value.

1. The credentials profile with the name specified by the `AWS_PROFILE` environment variable.

1. The default profile, in the following order:

   1. The `default` profile in the AWS SDK store.

   1. The `default` profile in the shared AWS `credentials` file.

   1. The `AWS PS Default` profile in the AWS SDK store.

1. If the command is running on an Amazon EC2 instance that is configured to use an IAM role, the EC2 instance's temporary credentials accessed from the instance profile.

   For more information about using IAM roles for Amazon EC2 instances, see [Granting access with a role](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-hosm.html) in the [AWS SDK for .NET Developer Guide](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/).

If this search fails to locate the specified credentials, the command throws an exception.

For additional information about environment variables and credentials profiles, see the following topics in the [AWS SDKs and Tools Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/): [Environment variables](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html), [Environment variables list](https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html#EVarSettings), and [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html).

# Configure federated identity with the AWS Tools for PowerShell
<a name="saml-pst"></a>

To let users in your organization access AWS resources, you must configure a standard and repeatable authentication method for purposes of security, auditability, compliance, and the capability to support role and account separation. Although it's common to provide users with the ability to access AWS APIs, without federated API access, you would also have to create AWS Identity and Access Management (IAM) users, which defeats the purpose of using federation. This topic describes SAML (Security Assertion Markup Language) support in the AWS Tools for PowerShell that eases your federated access solution.

SAML support in the AWS Tools for PowerShell lets you provide your users federated access to AWS services. SAML is an XML-based, open-standard format for transmitting user authentication and authorization data between services; in particular, between an identity provider (such as [Active Directory Federation Services](https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/ad-fs-overview)), and a service provider (such as AWS). For more information about SAML and how it works, see [SAML](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language) on Wikipedia, or [SAML Technical Specifications](https://www.oasis-open.org/standard/saml/) at the Organization for the Advancement of Structured Information Standards (OASIS) website. SAML support in the AWS Tools for PowerShell is compatible with SAML 2.0.

## Prerequisites
<a name="saml-pst-prerequisites"></a>

You must have the following in place before you try to use SAML support for the first time.
+ A federated identity solution that is correctly integrated with your AWS account for console access by using only your organizational credentials. For more information about how to do this specifically for Active Directory Federation Services, see [About SAML 2.0 Federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) in the *IAM User Guide*, and the blog post, [Enabling Federation to AWS Using Windows Active Directory, AD FS, and SAML 2.0](https://aws.amazon.com/blogs/security/enabling-federation-to-aws-using-windows-active-directory-adfs-and-saml-2-0/). Although the blog post covers AD FS 2.0, the steps are similar if you are running AD FS 3.0.
+ Version 3.1.31.0 or newer of the AWS Tools for PowerShell installed on your local workstation.

## How an Identity-Federated User Gets Federated Access to AWS Service APIs
<a name="saml-pst-federated-process"></a>

The following process describes, at a high level, how an Active Directory (AD) user is federated by AD FS to gain access to AWS resources.

![\[Diagram showing federated user access flow to AWS resources via AD FS and Security Token Service.\]](http://docs.aws.amazon.com/powershell/v5/userguide/images/powershell_ADFSauth_using_vsd.png)


1. The client on federated user's computer authenticates against AD FS.

1. If authentication succeeds, AD FS sends the user a SAML assertion.

1. The user's client sends the SAML assertion to the AWS Security Token Service (STS) as part of a SAML federation request.

1. STS returns a SAML response that contains AWS temporary credentials for a role the user can assume.

1. The user accesses AWS service APIs by including those temporary credentials in request made by AWS Tools for PowerShell.

## How SAML Support Works in the AWS Tools for PowerShell
<a name="saml-pst-overview"></a>

This section describes how AWS Tools for PowerShell cmdlets enable configuration of SAML-based identity federation for users.

![\[Diagram showing SAML-based federation flow between organization, AD FS, AWS, and service APIs.\]](http://docs.aws.amazon.com/powershell/v5/userguide/images/Powershell_SamlAuth_using_vsd.png)


1. AWS Tools for PowerShell authenticates against AD FS by using the Windows user's current credentials, or interactively, when the user tries to run a cmdlet that requires credentials to call into AWS.

1. AD FS authenticates the user.

1. AD FS generates a SAML 2.0 authentication response that includes an assertion; the purpose of the assertion is to identify and provide information about the user. AWS Tools for PowerShell extracts the list of the user's authorized roles from the SAML assertion.

1. AWS Tools for PowerShell forwards the SAML request, including the requested role's Amazon Resource Names (ARN), to STS by making the `AssumeRoleWithSAMLRequest` API call.

1. If the SAML request is valid, STS returns a response that contains the AWS `AccessKeyId`, `SecretAccessKey`, and `SessionToken`. These credentials last for 3,600 seconds (1 hour).

1. The user now has valid credentials to work with any AWS service APIs that the user's role is authorized to access. AWS Tools for PowerShell automatically applies these credentials for any subsequent AWS API calls, and renews them automatically when they expire.
**Note**  
When the credentials expire, and new credentials are required, AWS Tools for PowerShell automatically reauthenticates with AD FS, and obtains new credentials for a subsequent hour. For users of domain-joined accounts, this process occurs silently. For accounts that are not domain-joined, AWS Tools for PowerShell prompts users to enter their credentials before they can reauthenticate.

## How to Use the PowerShell SAML Configuration Cmdlets
<a name="saml-pst-config-cmdlets"></a>

AWS Tools for PowerShell includes two new cmdlets that provide SAML support.
+  `Set-AWSSamlEndpoint` configures your AD FS endpoint, assigns a friendly name to the endpoint, and optionally describes the authentication type of the endpoint.
+  `Set-AWSSamlRoleProfile` creates or edits a user account profile that you want to associate with an AD FS endpoint, identified by specifying the friendly name you provided to the `Set-AWSSamlEndpoint` cmdlet. Each role profile maps to a single role that a user is authorized to perform.

  Just as with AWS credential profiles, you assign a friendly name to the role profile. You can use the same friendly name with the `Set-AWSCredential` cmdlet, or as the value of the `-ProfileName` parameter for any cmdlet that invokes AWS service APIs.

Open a new AWS Tools for PowerShell session. If you are running PowerShell 3.0 or newer, the AWS Tools for PowerShell module is automatically imported when you run any of its cmdlets. If you are running PowerShell 2.0, you must import the module manually by running the ``Import-Module`` cmdlet, as shown in the following example.

```
PS > Import-Module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1"
```

### How to Run the `Set-AWSSamlEndpoint` and `Set-AWSSamlRoleProfile` Cmdlets
<a name="how-to-run-the-set-awssamlendpoint-and-set-awssamlroleprofile-cmdlets"></a>

1. First, configure the endpoint settings for the AD FS system. The simplest way to do this is to store the endpoint in a variable, as shown in this step. Be sure to replace the placeholder account IDs and AD FS host name with your own account IDs and AD FS host name. Specify the AD FS host name in the `Endpoint` parameter.

   ```
   PS > $endpoint = "https://adfs.example.com/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices"
   ```

1. To create the endpoint settings, run the `Set-AWSSamlEndpoint` cmdlet, specifying the correct value for the `AuthenticationType` parameter. Valid values include `Basic`, `Digest`, `Kerberos`, `Negotiate`, and `NTLM`. If you do not specify this parameter, the default value is `Kerberos`.

   ```
   PS > $epName = Set-AWSSamlEndpoint -Endpoint $endpoint -StoreAs ADFS-Demo -AuthenticationType NTLM
   ```

   The cmdlet returns the friendly name you assigned by using the `-StoreAs` parameter, so you can use it when you run `Set-AWSSamlRoleProfile` in the next line.

1. Now, run the `Set-AWSSamlRoleProfile` cmdlet to authenticate with the AD FS identity provider and get the set of roles (in the SAML assertion) that the user is authorized to perform.

   The `Set-AWSSamlRoleProfile` cmdlet uses the returned set of roles to either prompt the user to select a role to associate with the specified profile, or validate that role data provided in parameters is present (if not, the user is prompted to choose). If the user is authorized for only one role, the cmdlet associates the role with the profile automatically, without prompting the user. There is no need to provide a credential to set up a profile for domain-joined usage.

   ```
   PS > Set-AWSSamlRoleProfile -StoreAs SAMLDemoProfile -EndpointName $epName
   ```

   Alternatively, for non-domain-joined accounts, you can provide Active Directory credentials, and then select an AWS role to which the user has access, as shown in the following line. This is useful if you have different Active Directory user accounts to differentiate roles within your organization (for example, administration functions).

   ```
   PS > $credential = Get-Credential -Message "Enter the domain credentials for the endpoint"
   PS > Set-AWSSamlRoleProfile -EndpointName $epName -NetworkCredential $credential -StoreAs SAMLDemoProfile
   ```

1. In either case, the `Set-AWSSamlRoleProfile` cmdlet prompts you to choose which role should be stored in the profile. The following example shows two available roles: `ADFS-Dev`, and `ADFS-Production`. The IAM roles are associated with your AD login credentials by the AD FS administrator.

   ```
   Select Role
   Select the role to be assumed when this profile is active
   [1] 1 - ADFS-Dev  [2] 2 - ADFS-Production  [?] Help (default is "1"):
   ```

   Alternatively, you can specify a role without the prompt, by entering the `RoleARN`, `PrincipalARN`, and optional `NetworkCredential` parameters. If the specified role is not listed in the assertion returned by authentication, the user is prompted to choose from available roles.

   ```
   PS > $params = @{ "NetworkCredential"=$credential, "PrincipalARN"="{arn:aws:iam::012345678912:saml-provider/ADFS}", "RoleARN"="{arn:aws:iam::012345678912:role/ADFS-Dev}"
   }
   PS > $epName | Set-AWSSamlRoleProfile @params -StoreAs SAMLDemoProfile1 -Verbose
   ```

1. You can create profiles for all roles in a single command by adding the `StoreAllRoles` parameter, as shown in the following code. Note that the role name is used as the profile name.

   ```
   PS > Set-AWSSamlRoleProfile -EndpointName $epName -StoreAllRoles
   ADFS-Dev
   ADFS-Production
   ```

### How to Use Role Profiles to Run Cmdlets that Require AWS Credentials
<a name="how-to-use-role-profiles-to-run-cmdlets-that-require-aws-credentials"></a>

To run cmdlets that require AWS credentials, you can use role profiles defined in the AWS shared credential file. Provide the name of a role profile to `Set-AWSCredential` (or as the value for any `ProfileName` parameter in the AWS Tools for PowerShell) to get temporary AWS credentials automatically for the role that is described in the profile.

Although you use only one role profile at a time, you can switch between profiles within a shell session. The `Set-AWSCredential` cmdlet does not authenticate and get credentials when you run it by itself; the cmdlet records that you want to use a specified role profile. Until you run a cmdlet that requires AWS credentials, no authentication or request for credentials occurs.

You can now use the temporary AWS credentials that you obtained with the `SAMLDemoProfile` profile to work with AWS service APIs. The following sections show examples of how to use role profiles.

### Example 1: Set a Default Role with `Set-AWSCredential`
<a name="example-1-set-a-default-role-with-set-awscredential"></a>

This example sets a default role for a AWS Tools for PowerShell session by using `Set-AWSCredential`. Then, you can run cmdlets that require credentials, and are authorized by the specified role. This example lists all Amazon Elastic Compute Cloud instances in the US West (Oregon) Region that are associated with the profile you specified with the `Set-AWSCredential` cmdlet.

```
PS > Set-AWSCredential -ProfileName SAMLDemoProfile
PS > Get-EC2Instance -Region us-west-2 | Format-Table -Property Instances,GroupNames

Instances                                                   GroupNames
---------                                                   ----------
{TestInstance1}                                             {default}
{TestInstance2}                                             {}
{TestInstance3}                                             {launch-wizard-6}
{TestInstance4}                                             {default}
{TestInstance5}                                             {}
{TestInstance6}                                             {AWS-OpsWorks-Default-Server}
```

### Example 2: Change Role Profiles During a PowerShell Session
<a name="example-2-change-role-profiles-during-a-powershell-session"></a>

This example lists all available Amazon S3 buckets in the AWS account of the role associated with the `SAMLDemoProfile` profile. The example shows that although you might have been using another profile earlier in your AWS Tools for PowerShell session, you can change profiles by specifying a different value for the `-ProfileName` parameter with cmdlets that support it. This is a common task for administrators who manage Amazon S3 from the PowerShell command line.

```
PS > Get-S3Bucket -ProfileName SAMLDemoProfile

CreationDate                                                BucketName
------------                                                ----------
7/25/2013 3:16:56 AM                                        amzn-s3-demo-bucket
4/15/2015 12:46:50 AM                                       amzn-s3-demo-bucket1
4/15/2015 6:15:53 AM                                        amzn-s3-demo-bucket2
1/12/2015 11:20:16 PM                                       amzn-s3-demo-bucket3
```

Note that the `Get-S3Bucket` cmdlet specifies the name of the profile created by running the `Set-AWSSamlRoleProfile` cmdlet. This command could be useful if you had set a role profile earlier in your session (for example, by running the `Set-AWSCredential` cmdlet) and wanted to use a different role profile for the `Get-S3Bucket` cmdlet. The profile manager makes temporary credentials available to the `Get-S3Bucket` cmdlet.

Although the credentials expire after 1 hour (a limit enforced by STS), AWS Tools for PowerShell automatically refreshes the credentials by requesting a new SAML assertion when the tool detects that the current credentials have expired.

For domain-joined users, this process occurs without interruption, because the current user's Windows identity is used during authentication. For non-domain-joined user accounts, AWS Tools for PowerShell shows a PowerShell credential prompt requesting the user password. The user provides credentials that are used to reauthenticate the user and get a new assertion.

### Example 3: Get Instances in a Region
<a name="example-3-get-instances-in-a-region"></a>

The following example lists all Amazon EC2 instances in the Asia Pacific (Sydney) Region that are associated with the account used by the `ADFS-Production` profile. This is a useful command for returning all Amazon EC2 instances in a region.

```
PS > (Get-Ec2Instance -ProfileName ADFS-Production -Region ap-southeast-2).Instances | Select InstanceType, @{Name="Servername";Expression={$_.tags | where key -eq "Name" | Select Value -Expand Value}}

 InstanceType                                                Servername
 ------------                                                ----------
 t2.small                                                    DC2
 t1.micro                                                    NAT1
 t1.micro                                                    RDGW1
 t1.micro                                                    RDGW2
 t1.micro                                                    NAT2
 t2.small                                                    DC1
 t2.micro                                                    BUILD
```

## Additional Reading
<a name="saml-pst-reading"></a>

For general information about how to implement federated API access, see [How to Implement a General Solution for Federated API/CLI Access Using SAML 2.0](https://aws.amazon.com/blogs/security/how-to-implement-a-general-solution-for-federated-apicli-access-using-saml-2-0/).

For support questions or comments, visit the AWS Developer Forums for [PowerShell Scripting](https://forums.aws.amazon.com/forum.jspa?forumID=149) or [.NET Development](https://forums.aws.amazon.com/forum.jspa?forumID=61).

# Observability
<a name="observability"></a>

Observability is the extent to which a system's current state can be inferred from the data it emits. The data emitted is commonly referred to as telemetry. For additional information about telemetry when using AWS services, see [Observability](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/observability.html) in the [AWS SDK for .NET Developer Guide](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/).

The following code shows an example of how observability can be enabled in the AWS Tools for PowerShell.

```
<#
    This is an example of generating telemetry for AWS Tools for PowerShell.
    Each cmdlet that interacts with an Amazon Web Service creates a trace containing spans
    for underlying processes and AWS SDK for .NET operations.
    This example is written using PowerShell 7 and .NET 8.
    It requires the installation of the .NET CLI tool.
    Note that implementation varies by the exporter/endpoint, which is not specified in this example.
    For more information, see https://opentelemetry.io/docs/languages/net/exporters/.
#>

# Set this value to a common folder path on your computer for local development of code repositories.
$devProjectsPath = [System.IO.Path]::Join('C:', 'Dev', 'Repos')

# If these values are changed, update the hardcoded method invocation toward the end of this script.
# Values must follow constraints for namespaces and classes.
$telemetryProjectName = 'ExampleAWSPowerShellTelemetryImplementation'
$serviceName = 'ExamplePowerShellService'

# This example supposes that the OTLP exporter requires these two properties,
# but some exporters require different properties or no properties.
$telemetryEndPoint = 'https://example-endpoint-provider.io'
$telemetryHeaders = 'x-example-header=abc123'

$dllsPath = [System.IO.Path]::Join($devProjectsPath, $telemetryProjectName, 'bin', 'Release', 'net8.0', 'publish')

$telemetryProjectPath = [System.IO.Path]::Join($devProjectsPath, $telemetryProjectName)

# This script is designed to recreate the example telemetry project each time it's executed.
Remove-Item -Path $telemetryProjectPath -Recurse -Force -ErrorAction 'SilentlyContinue'
$null = New-Item -Path $devProjectsPath -Name $telemetryProjectName -ItemType 'Directory'

<#
    Create and build a C#-based .NET 8 project that implements
    OpenTelemetry Instrumentation for the AWS Tools for PowerShell.
#>

Set-Location -Path $telemetryProjectPath

dotnet new classlib

# Other exporters are available.
# For more information, see https://opentelemetry.io/docs/languages/net/exporters/.
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Instrumentation.AWS

$classContent = @"
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

namespace Example.Telemetry;

public class AWSToolsForPowerShellTelemetry
{
    public static void InitializeAWSInstrumentation()
    {
        Sdk.CreateTracerProviderBuilder()
        .ConfigureResource(e => e.AddService("$ServiceName"))
        .AddAWSInstrumentation()
        // Exporters vary so options might need to be changed or omitted.
        .AddOtlpExporter(options =>
        {
            options.Endpoint = new Uri("$telemetryEndPoint");
            options.Headers = "$telemetryHeaders";
        })
        .Build();
    }
}
"@

$csFilePath = [System.IO.Path]::Join($telemetryProjectPath, ($serviceName + '.cs'))
Set-Content -Path $csFilePath -Value $classContent

dotnet build
dotnet publish -c Release

<#
    Add additional modules here for any other cmdlets that you require. 
    Beyond this point, additional AWS Tools for PowerShell modules will fail to import
    due to conflicts with the AWS SDK for .NET assemblies that are added next.
#>

Import-Module -Name 'AWS.Tools.Common'
Import-Module -Name 'AWS.Tools.DynamoDBv2'


# Load assemblies for the telemetry project, excluding the AWS SDK for .NET assemblies
# that were already loaded by importing AWS Tools for PowerShell modules.
$dlls = (Get-ChildItem $dllsPath -Filter *.dll -Recurse ).FullName
$AWSSDKAssembliesAlreadyLoaded = [Threading.Thread]::GetDomain().GetAssemblies().Location | Where-Object {$_ -like '*AWSSDK*' } | Split-Path -Leaf
$dlls.Where{$AWSSDKAssembliesAlreadyLoaded -notcontains ($_ | Split-Path -Leaf)}.ForEach{Add-Type -Path $_}

# Invoke the method defined earlier in this script.
[Example.Telemetry.AWSToolsForPowerShellTelemetry]::InitializeAWSInstrumentation()

<#
    Now telemetry will be exported for AWS Tools for PowerShell cmdlets
    that are invoked directly or indirectly.
    Execute this cmdlet or execute your own PowerShell script.
#>
Get-DDBTable -TableName 'DotNetTests-HashTable' -Region 'us-east-1'
```

# Cmdlet discovery and aliases
<a name="pstools-discovery-aliases"></a>

This section shows you how to list services that are supported by the AWS Tools for PowerShell, how to show the set of cmdlets provided by the AWS Tools for PowerShell in support of those services, and how to find alternative cmdlet names (also called aliases) to access those services.

## Cmdlet Discovery
<a name="pstools-cmdlet-discovery"></a>

All AWS service operations (or APIs) are documented in the API Reference Guide for each service. For example, see the [IAM API Reference](https://docs.aws.amazon.com/IAM/latest/APIReference/). There is, in most cases, a one-to-one correspondence between an AWS service API and an AWS PowerShell cmdlet. To get the cmdlet name that corresponds to an AWS service API name, run the AWS `Get-AWSCmdletName` cmdlet with the `-ApiOperation` parameter and the AWS service API name. For example, to get all possible cmdlet names that are based on any available `DescribeInstances` AWS service API, run the following command:

```
PS > Get-AWSCmdletName -ApiOperation DescribeInstances

CmdletName        ServiceOperation    ServiceName                    CmdletNounPrefix
----------        ----------------    -----------                    ----------------
Get-EC2Instance   DescribeInstances   Amazon Elastic Compute Cloud   EC2
Get-GMLInstance   DescribeInstances   Amazon GameLift Service        GML
```

The `-ApiOperation` parameter is the default parameter, so you can omit the parameter name. The following example is equivalent to the previous one:

```
PS > Get-AWSCmdletName DescribeInstances
```

If you know the names of both the API and the service, you can include the `-Service` parameter along with either the cmdlet noun prefix or part of the AWS service name. For example, the cmdlet noun prefix for Amazon EC2 is `EC2`. To get the cmdlet name that corresponds to the `DescribeInstances` API in the Amazon EC2 service, run one of the following commands. They are all result in the same output:

```
PS > Get-AWSCmdletName -ApiOperation DescribeInstances -Service EC2
PS > Get-AWSCmdletName -ApiOperation DescribeInstances -Service Compute
PS > Get-AWSCmdletName -ApiOperation DescribeInstances -Service "Compute Cloud"

CmdletName        ServiceOperation    ServiceName                    CmdletNounPrefix
----------        ----------------    -----------                    ----------------
Get-EC2Instance   DescribeInstances   Amazon Elastic Compute Cloud   EC2
```

Parameter values in these commands are case-insensitive.

If you do not know the name of either the desired AWS service API or the AWS service, you can use the `-ApiOperation` parameter, along with the pattern to match, and the `-MatchWithRegex` parameter. For example, to get all available cmdlet names that contain `SecurityGroup`, run the following command:

```
PS > Get-AWSCmdletName -ApiOperation SecurityGroup -MatchWithRegex

CmdletName                                    ServiceOperation                            ServiceName                        CmdletNounPrefix
----------                                    ----------------                            -----------                        ----------------
Approve-ECCacheSecurityGroupIngress           AuthorizeCacheSecurityGroupIngress          Amazon ElastiCache                 EC
Get-ECCacheSecurityGroup                      DescribeCacheSecurityGroups                 Amazon ElastiCache                 EC
New-ECCacheSecurityGroup                      CreateCacheSecurityGroup                    Amazon ElastiCache                 EC
Remove-ECCacheSecurityGroup                   DeleteCacheSecurityGroup                    Amazon ElastiCache                 EC
Revoke-ECCacheSecurityGroupIngress            RevokeCacheSecurityGroupIngress             Amazon ElastiCache                 EC
Add-EC2SecurityGroupToClientVpnTargetNetwrk   ApplySecurityGroupsToClientVpnTargetNetwork Amazon Elastic Compute Cloud       EC2
Get-EC2SecurityGroup                          DescribeSecurityGroups                      Amazon Elastic Compute Cloud       EC2
Get-EC2SecurityGroupReference                 DescribeSecurityGroupReferences             Amazon Elastic Compute Cloud       EC2
Get-EC2StaleSecurityGroup                     DescribeStaleSecurityGroups                 Amazon Elastic Compute Cloud       EC2
Grant-EC2SecurityGroupEgress                  AuthorizeSecurityGroupEgress                Amazon Elastic Compute Cloud       EC2
Grant-EC2SecurityGroupIngress                 AuthorizeSecurityGroupIngress               Amazon Elastic Compute Cloud       EC2
New-EC2SecurityGroup                          CreateSecurityGroup                         Amazon Elastic Compute Cloud       EC2
Remove-EC2SecurityGroup                       DeleteSecurityGroup                         Amazon Elastic Compute Cloud       EC2
Revoke-EC2SecurityGroupEgress                 RevokeSecurityGroupEgress                   Amazon Elastic Compute Cloud       EC2
Revoke-EC2SecurityGroupIngress                RevokeSecurityGroupIngress                  Amazon Elastic Compute Cloud       EC2
Update-EC2SecurityGroupRuleEgressDescription  UpdateSecurityGroupRuleDescriptionsEgress   Amazon Elastic Compute Cloud       EC2
Update-EC2SecurityGroupRuleIngressDescription UpdateSecurityGroupRuleDescriptionsIngress  Amazon Elastic Compute Cloud       EC2
Edit-EFSMountTargetSecurityGroup              ModifyMountTargetSecurityGroups             Amazon Elastic File System         EFS
Get-EFSMountTargetSecurityGroup               DescribeMountTargetSecurityGroups           Amazon Elastic File System         EFS
Join-ELBSecurityGroupToLoadBalancer           ApplySecurityGroupsToLoadBalancer           Elastic Load Balancing             ELB
Set-ELB2SecurityGroup                         SetSecurityGroups                           Elastic Load Balancing V2          ELB2
Enable-RDSDBSecurityGroupIngress              AuthorizeDBSecurityGroupIngress             Amazon Relational Database Service RDS
Get-RDSDBSecurityGroup                        DescribeDBSecurityGroups                    Amazon Relational Database Service RDS
New-RDSDBSecurityGroup                        CreateDBSecurityGroup                       Amazon Relational Database Service RDS
Remove-RDSDBSecurityGroup                     DeleteDBSecurityGroup                       Amazon Relational Database Service RDS
Revoke-RDSDBSecurityGroupIngress              RevokeDBSecurityGroupIngress                Amazon Relational Database Service RDS
Approve-RSClusterSecurityGroupIngress         AuthorizeClusterSecurityGroupIngress        Amazon Redshift                    RS
Get-RSClusterSecurityGroup                    DescribeClusterSecurityGroups               Amazon Redshift                    RS
New-RSClusterSecurityGroup                    CreateClusterSecurityGroup                  Amazon Redshift                    RS
Remove-RSClusterSecurityGroup                 DeleteClusterSecurityGroup                  Amazon Redshift                    RS
Revoke-RSClusterSecurityGroupIngress          RevokeClusterSecurityGroupIngress           Amazon Redshift                    RS
```

If you know the name of the AWS service but not the AWS service API, include both the `-MatchWithRegex` parameter and the `-Service` parameter to scope the search down to a single service. For example, to get all cmdlet names that contain `SecurityGroup` in only the Amazon EC2 service, run the following command

```
PS > Get-AWSCmdletName -ApiOperation SecurityGroup -MatchWithRegex -Service EC2

CmdletName                                    ServiceOperation                            ServiceName                  CmdletNounPrefix
----------                                    ----------------                            -----------                  ----------------
Add-EC2SecurityGroupToClientVpnTargetNetwrk   ApplySecurityGroupsToClientVpnTargetNetwork Amazon Elastic Compute Cloud EC2
Get-EC2SecurityGroup                          DescribeSecurityGroups                      Amazon Elastic Compute Cloud EC2
Get-EC2SecurityGroupReference                 DescribeSecurityGroupReferences             Amazon Elastic Compute Cloud EC2
Get-EC2StaleSecurityGroup                     DescribeStaleSecurityGroups                 Amazon Elastic Compute Cloud EC2
Grant-EC2SecurityGroupEgress                  AuthorizeSecurityGroupEgress                Amazon Elastic Compute Cloud EC2
Grant-EC2SecurityGroupIngress                 AuthorizeSecurityGroupIngress               Amazon Elastic Compute Cloud EC2
New-EC2SecurityGroup                          CreateSecurityGroup                         Amazon Elastic Compute Cloud EC2
Remove-EC2SecurityGroup                       DeleteSecurityGroup                         Amazon Elastic Compute Cloud EC2
Revoke-EC2SecurityGroupEgress                 RevokeSecurityGroupEgress                   Amazon Elastic Compute Cloud EC2
Revoke-EC2SecurityGroupIngress                RevokeSecurityGroupIngress                  Amazon Elastic Compute Cloud EC2
Update-EC2SecurityGroupRuleEgressDescription  UpdateSecurityGroupRuleDescriptionsEgress   Amazon Elastic Compute Cloud EC2
Update-EC2SecurityGroupRuleIngressDescription UpdateSecurityGroupRuleDescriptionsIngress  Amazon Elastic Compute Cloud EC2
```

If you know the name of the AWS Command Line Interface (AWS CLI) command, you can use the `-AwsCliCommand` parameter and the desired AWS CLI command name to get the name of the cmdlet that's based on the same API. For example, to get the cmdlet name that corresponds to the `authorize-security-group-ingress` AWS CLI command call in the Amazon EC2 service, run the following command:

```
PS > Get-AWSCmdletName -AwsCliCommand "aws ec2 authorize-security-group-ingress"

CmdletName                    ServiceOperation              ServiceName                  CmdletNounPrefix
----------                    ----------------              -----------                  ----------------
Grant-EC2SecurityGroupIngress AuthorizeSecurityGroupIngress Amazon Elastic Compute Cloud EC2
```

The `Get-AWSCmdletName` cmdlet needs only enough of the AWS CLI command name to identify the service and the AWS API. 

To get a list of all of the cmdlets in the Tools for PowerShell Core, run the PowerShell `Get-Command` cmdlet, as shown in the following example.

```
PS > Get-Command -Module AWSPowerShell.NetCore
```

You can run the same command with `-Module AWSPowerShell` to see the cmdlets in the AWS Tools for Windows PowerShell.

The `Get-Command` cmdlet generates the list of cmdlets in alphabetical order. Note that by default the list is sorted by PowerShell verb, rather than PowerShell noun.

To sort results by service instead, run the following command:

```
PS > Get-Command -Module AWSPowerShell.NetCore | Sort-Object Noun,Verb
```

To filter the cmdlets that are returned by the `Get-Command` cmdlet, pipe the output to the PowerShell `Select-String` cmdlet. For example, to view the set of cmdlets that work with AWS regions, run the following command:

```
PS > Get-Command -Module AWSPowerShell.NetCore | Select-String region

Clear-DefaultAWSRegion
Copy-HSM2BackupToRegion
Get-AWSRegion
Get-DefaultAWSRegion
Get-EC2Region
Get-LSRegionList
Get-RDSSourceRegion
Set-DefaultAWSRegion
```

You can also find cmdlets for a specific service by filtering for the service prefix of cmdlet nouns. To see the list of available service prefixes, run `Get-AWSPowerShellVersion -ListServiceVersionInfo`. The following example returns cmdlets that support the Amazon CloudWatch Events service.

```
PS > Get-Command -Module AWSPowerShell -Noun CWE*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Add-CWEResourceTag                                 3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Disable-CWEEventSource                             3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Disable-CWERule                                    3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Enable-CWEEventSource                              3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Enable-CWERule                                     3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEEventBus                                    3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEEventBusList                                3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEEventSource                                 3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEEventSourceList                             3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEPartnerEventSource                          3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEPartnerEventSourceAccountList               3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEPartnerEventSourceList                      3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWEResourceTag                                 3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWERule                                        3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWERuleDetail                                  3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWERuleNamesByTarget                           3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Get-CWETargetsByRule                               3.3.563.1  AWSPowerShell.NetCore
Cmdlet          New-CWEEventBus                                    3.3.563.1  AWSPowerShell.NetCore
Cmdlet          New-CWEPartnerEventSource                          3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Remove-CWEEventBus                                 3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Remove-CWEPartnerEventSource                       3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Remove-CWEPermission                               3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Remove-CWEResourceTag                              3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Remove-CWERule                                     3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Remove-CWETarget                                   3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Test-CWEEventPattern                               3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Write-CWEEvent                                     3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Write-CWEPartnerEvent                              3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Write-CWEPermission                                3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Write-CWERule                                      3.3.563.1  AWSPowerShell.NetCore
Cmdlet          Write-CWETarget                                    3.3.563.1  AWSPowerShell.NetCore
```

## Cmdlet Naming and Aliases
<a name="pstools-cmdlet-naming-aliases"></a>

The cmdlets in the AWS Tools for PowerShell for each service are based on the methods provided by the AWS SDK for the service. However, because of PowerShell's mandatory naming conventions, the name of a cmdlet might be different from the name of the API call or method on which it is based. For example, the `Get-EC2Instance` cmdlet is based on the Amazon EC2`DescribeInstances` method.

In some cases, the cmdlet name may be similar to a method name, but it may actually perform a different function. For example, the Amazon S3`GetObject` method retrieves an Amazon S3 object. However, the `Get-S3Object` cmdlet returns *information* about an Amazon S3 object rather than the object itself.

```
PS > Get-S3Object -BucketName text-content -Key aws-tech-docs

ETag         : "df000002a0fe0000f3c000004EXAMPLE"
BucketName   : aws-tech-docs
Key          : javascript/frameset.js
LastModified : 6/13/2011 1:24:18 PM
Owner        : Amazon.S3.Model.Owner
Size         : 512
StorageClass : STANDARD
```

To get an S3 object with the AWS Tools for PowerShell, run the `Read-S3Object` cmdlet:

```
PS > Read-S3Object -BucketName text-content -Key text-object.txt -file c:\tmp\text-object-download.text

Mode          LastWriteTime            Length Name
----          -------------            ------ ----
-a---         11/5/2012   7:29 PM      20622  text-object-download.text
```

**Note**  
The cmdlet help for an AWS cmdlet provides the name of the AWS SDK API on which the cmdlet is based.  
For more information about standard PowerShell verbs and their meanings, see [Approved Verbs for PowerShell Commands](https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands).

All AWS cmdlets that use the `Remove` verb – and the `Stop-EC2Instance` cmdlet when you add the `-Terminate` parameter – prompt for confirmation before proceeding. To bypass confirmation, add the `-Force` parameter to your command.

**Important**  
AWS cmdlets do not support the `-WhatIf` switch.

### Aliases
<a name="pstools-aliases"></a>

Setup of the AWS Tools for PowerShell installs an aliases file that contains aliases for many of the AWS cmdlets. You might find these aliases to be more intuitive than the cmdlet names. For example, service names and AWS SDK method names replace PowerShell verbs and nouns in some aliases. An example is the `EC2-DescribeInstances` alias.

Other aliases use verbs that, though they do not follow standard PowerShell conventions, can be more descriptive of the actual operation. For example, the alias file maps the alias `Get-S3Content` to the cmdlet `Read-S3Object`.

```
PS > Set-Alias -Name Get-S3Content -Value Read-S3Object
```

The aliases file is located in the AWS Tools for PowerShell installation directory. To load the aliases into your environment, *dot-source* the file. The following is a Windows-based example.

```
PS > . "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowershell\AWSAliases.ps1"
```

For a Linux or macOS shell, it might look like this:

```
. ~/.local/share/powershell/Modules/AWSPowerShell.NetCore/3.3.563.1/AWSAliases.ps1
```

To show all AWS Tools for PowerShell aliases, run the following command. This command uses the `?` alias for the PowerShell `Where-Object` cmdlet and the `Source` property to filter for only aliases that come from the `AWSPowerShell.NetCore` module.

```
PS > Get-Alias | ? Source -like "AWSPowerShell.NetCore"

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           Add-ASInstances                                    3.3.343.0  AWSPowerShell
Alias           Add-CTTag                                          3.3.343.0  AWSPowerShell
Alias           Add-DPTags                                         3.3.343.0  AWSPowerShell
Alias           Add-DSIpRoutes                                     3.3.343.0  AWSPowerShell
Alias           Add-ELBTags                                        3.3.343.0  AWSPowerShell
Alias           Add-EMRTag                                         3.3.343.0  AWSPowerShell
Alias           Add-ESTag                                          3.3.343.0  AWSPowerShell
Alias           Add-MLTag                                          3.3.343.0  AWSPowerShell
Alias           Clear-AWSCredentials                               3.3.343.0  AWSPowerShell
Alias           Clear-AWSDefaults                                  3.3.343.0  AWSPowerShell
Alias           Dismount-ASInstances                               3.3.343.0  AWSPowerShell
Alias           Edit-EC2Hosts                                      3.3.343.0  AWSPowerShell
Alias           Edit-RSClusterIamRoles                             3.3.343.0  AWSPowerShell
Alias           Enable-ORGAllFeatures                              3.3.343.0  AWSPowerShell
Alias           Find-CTEvents                                      3.3.343.0  AWSPowerShell
Alias           Get-ASACases                                       3.3.343.0  AWSPowerShell
Alias           Get-ASAccountLimits                                3.3.343.0  AWSPowerShell
Alias           Get-ASACommunications                              3.3.343.0  AWSPowerShell
Alias           Get-ASAServices                                    3.3.343.0  AWSPowerShell
Alias           Get-ASASeverityLevels                              3.3.343.0  AWSPowerShell
Alias           Get-ASATrustedAdvisorCheckRefreshStatuses          3.3.343.0  AWSPowerShell
Alias           Get-ASATrustedAdvisorChecks                        3.3.343.0  AWSPowerShell
Alias           Get-ASATrustedAdvisorCheckSummaries                3.3.343.0  AWSPowerShell
Alias           Get-ASLifecycleHooks                               3.3.343.0  AWSPowerShell
Alias           Get-ASLifecycleHookTypes                           3.3.343.0  AWSPowerShell
Alias           Get-AWSCredentials                                 3.3.343.0  AWSPowerShell
Alias           Get-CDApplications                                 3.3.343.0  AWSPowerShell
Alias           Get-CDDeployments                                  3.3.343.0  AWSPowerShell
Alias           Get-CFCloudFrontOriginAccessIdentities             3.3.343.0  AWSPowerShell
Alias           Get-CFDistributions                                3.3.343.0  AWSPowerShell
Alias           Get-CFGConfigRules                                 3.3.343.0  AWSPowerShell
Alias           Get-CFGConfigurationRecorders                      3.3.343.0  AWSPowerShell
Alias           Get-CFGDeliveryChannels                            3.3.343.0  AWSPowerShell
Alias           Get-CFInvalidations                                3.3.343.0  AWSPowerShell
Alias           Get-CFNAccountLimits                               3.3.343.0  AWSPowerShell
Alias           Get-CFNStackEvents                                 3.3.343.0  AWSPowerShell

...
```

To add your own aliases to this file, you might need to raise the value of PowerShell's `$MaximumAliasCount` [preference variable](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-6) to a value greater than 5500. The default value is 4096; you can raise it to a maximum of 32768. To do this, run the following.

```
PS > $MaximumAliasCount = 32768
```

To verify that your change was successful, enter the variable name to show its current value.

```
PS > $MaximumAliasCount
32768
```

# Pipelining, output, and iteration in the AWS Tools for PowerShell
<a name="pstools-pipelines"></a>

## Pipelining
<a name="pstools-pipelining"></a>

PowerShell encourages users to connect cmdlets into [pipelines](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines) that direct the output of one cmdlet into the input of the next. The following example shows this behavior when using the AWS Tools for PowerShell. The command gets and then stops all Amazon EC2 instances in the current default Region.

```
PS > Get-EC2Instance | Stop-EC2Instance
```

## Cmdlet output
<a name="pstools-output"></a>

To better support pipelining, some data from the responses of the AWS SDK for .NET might be discarded by default. The output from AWS Tools for PowerShell cmdlets isn't reshaped to include the service response and result instances as `Note` properties on the emitted collection object. Instead, for those calls that emit a single collection as output, the collection is now enumerated to the PowerShell pipeline. This means that the SDK response and result data cannot exist in the pipeline because there is no containing collection object to which it can be attached.

Although most users probably won't need this data, it can be useful for diagnostic purposes because you can see exactly what was sent to and received from the underlying AWS service calls that were made by the cmdlet. Cmdlets can use the `-Select *` parameter and argument to return the entire service response.

To illustrate how all data from a response can be returned, consider the following examples.

The first example simply returns a list of Amazon S3 buckets. This is the default behavior.

```
PS > Get-S3Bucket

CreationDate           BucketName
------------           ----------
9/22/2023 10:54:35 PM  amzn-s3-demo-bucket1
9/22/2023 11:04:37 AM  amzn-s3-demo-bucket2
9/22/2023 12:54:34 PM  amzn-s3-demo-bucket3
```

The second example returns an AWS SDK for .NET response object. Because `-Select *` was specified, the output includes the entire API response, which contains the collection of buckets in the `Buckets` property. In this example, the `Format-List` cmdlet isn't strictly necessary, but is present to ensure that all properties are displayed.

```
PS > Get-S3Bucket -Select * | Format-List

LoggedAt          : 10/1/2023 9:45:52 AM
Buckets           : {amzn-s3-demo-bucket1, amzn-s3-demo-bucket2,
                    amzn-s3-demo-bucket3}
Owner             : Amazon.S3.Model.Owner
ContinuationToken :
ResponseMetadata  : Amazon.Runtime.ResponseMetadata
ContentLength     : 0
HttpStatusCode    : OK
```

## Iteration through paged data
<a name="pstools-iteration"></a>

The following sections describe various types of iteration that are possible.

### Automatic iteration
<a name="pstools-iteration-auto"></a>

For service APIs that impose a default maximum number of returned objects for a given call or that support pageable result sets, most cmdlets implement automatic iteration, which enables the default behavior of "page-to-completion". In this scenario, a cmdlet makes as many calls as necessary on your behalf to return the complete data set to the pipeline.

In the following example, which uses the [Get-S3Object](https://docs.aws.amazon.com/powershell/v5/reference/index.html?page=Get-S3Object.html&tocid=Get-S3Object) cmdlet, the `$result` variable contains `S3Object` instances for every key in a bucket called `amzn-s3-demo-bucket1`, which is potentially a very large data set.

```
PS > $result = Get-S3Object -BucketName amzn-s3-demo-bucket1
```

The following example reduces the number of results for each page during automatic iteration from the default value of 1000 to 500. The example performs twice as many automatic iteration calls because only half as many results are returned for each call.

```
PS > $result = Get-S3Object -BucketName amzn-s3-demo-bucket1 -MaxKey 500
```

### Disable automatic iteration
<a name="pstools-iteration-disable-auto"></a>

If you want the Tools for PowerShell to return only the first page of data, you can add the `-NoAutoIteration` parameter to prevent additional pages of data from being returned.

The following example uses the `-NoAutoIteration` and `-MaxKey` parameters to limit the number of returned `S3Object` instances to no more than the first 500 found in the bucket.

```
PS > $result = Get-S3Object -BucketName amzn-s3-demo-bucket1 -MaxKey 500 -NoAutoIteration
```

To determine if more data was available but not returned, use the `-Select *` parameter and argument and check if there is a value in the next token property.

The following example returns `$true` if there are more than 500 objects in the bucket and `$false` otherwise.

```
PS > $result = Get-S3Object -BucketName amzn-s3-demo-bucket1 -MaxKey 500 -NoAutoIteration -Select *
PS > $null -eq $result.NextMarker
```

**Note**  
The names of the next token response property and cmdlet parameter vary between cmdlets. For details, refer to the help documentation for each cmdlet.

### Manual iteration
<a name="pstools-iteration-manual"></a>

The following example returns all S3 objects from a bucket using a [do](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_do) loop, which evaluates the condition after each iteration. The `do` loop performs iterations until `Get-S3Object` sets `$result.NextMarker` to `$null`, indicating that no more paged data remains. The output of the loop is assigned to the `$s3Objects` variable.

```
$s3Objects = do
{
    $splatParams = @{
        BucketName = 'amzn-s3-demo-bucket1'
        MaxKey = 500 
        Marker = $result.NextMarker 
        NoAutoIteration = $true
        Select = '*'
    }
    $result = Get-S3Object @splatParams
    
    $result.S3Objects
}
while ($null -ne $result.NextMarker)
```

This example uses PowerShell [splatting](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting) to avoid a long line of code that would be caused by declaring parameters and arguments in-line.

# Additional information about users and roles
<a name="pstools-users-roles"></a>

In order to run Tools for PowerShell commands on AWS, you need to have some combination of users, permission sets, and service roles that are appropriate for your tasks.

The specific users, permission sets, and service roles that you create, and the way in which you use them, will depend on your requirements. The following is some additional information about why they might be used and how to create them.

## Users and permission sets
<a name="net-dg-users-roles-user"></a>

Although it's possible to use an IAM user account with long-term credentials to access AWS services, this is no longer a best practice and should be avoided. Even during development, it is a best practice to create users and permission sets in AWS IAM Identity Center and use temporary credentials provided by an identity source.

For development, you can use the user that you created or were given in [Authenticating with AWS](creds-idc.md). If you have appropriate AWS Management Console permissions, you can also create different permission sets with least privilege for that user or create new users specifically for development projects, providing permission sets with least privilege. The course of action you choose, if any, depends on your circumstances.

For more information about these users and permissions sets and how to create them, see [Authentication and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) in the *AWS SDKs and Tools Reference Guide* and [Getting started](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) in the *AWS IAM Identity Center User Guide*.

## Service roles
<a name="net-dg-users-roles-service-role"></a>

You can set up an AWS service role to access AWS services on behalf of users. This type of access is appropriate if multiple people will be running your application remotely; for example, on an Amazon EC2 instance that you have created for this purpose.

The process for creating a service role varies depending on the situation, but is essentially the following.

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. Choose **Roles**, and then choose **Create role**.

1. Choose **AWS service**, find and select **EC2** (for example), and then choose the **EC2** use case (for example).

1. Choose **Next** and select the [appropriate policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) for the AWS services that your application will use.
**Warning**  
Do ***NOT*** choose the **AdministratorAccess** policy because that policy enables read and write permissions to almost everything in your account.

1. Choose **Next**. Enter a **Role name**, **Description**, and any tags you want.

   You can find information about tags in [Controlling access using AWS resource tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) in the [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/).

1. Choose **Create role**.

You can find high-level information about IAM roles in [IAM Identities (users, user groups, and roles)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html#id_iam-roles) in the [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/). Find detailed information about roles in the [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) topic.

# Using legacy credentials
<a name="pstools-cred-legacy"></a>

The topics in this section provide information about using long-term or short-term credentials without using AWS IAM Identity Center.

**Warning**  
To avoid security risks, don't use IAM users for authentication when developing purpose-built software or working with real data. Instead, use federation with an identity provider such as [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

**Note**  
The information in these topics is for circumstances where you need to obtain and manage short-term or long-term credentials manually. For additional information about short-term and long-term credentials, see [Other ways to authenticate](https://docs.aws.amazon.com/sdkref/latest/guide/access-users.html) in the *AWS SDKs and Tools Reference Guide*.  
For best security practices, use AWS IAM Identity Center, as described in [Authenticating with AWS](creds-idc.md).

## Important warnings and guidance for credentials
<a name="pstools-creds-warnings-and-guidelines"></a>

**Warnings for credentials**
+ ***Do NOT*** use your account's root credentials to access AWS resources. These credentials provide unrestricted account access and are difficult to revoke.
+ ***Do NOT*** put literal access keys or credential information in your commands or scripts. If you do, you create a risk of accidentally exposing your credentials.
+ Be aware that any credentials stored in the shared AWS `credentials` file, are stored in plaintext.

**Additional guidance for securely managing credentials**

For a general discussion of how to securely manage AWS credentials, see [AWS security credentials](https://docs.aws.amazon.com/general/latest/gr/Welcome.html#aws-security-credentials) in the [AWS General Reference](https://docs.aws.amazon.com/general/latest/gr/) and [Security best practices and use cases](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPracticesAndUseCases.html) in the [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/). In addition to those discussions, consider the following:
+ Create additional users, such as users in IAM Identity Center, and use their credentials instead of using your AWS root user credentials. Credentials for other users can be revoked if necessary or are temporary by nature. In addition, you can apply a policy to each user for access to only certain resources and actions and thereby take a stance of least-privilege permissions.
+ Use [IAM roles for tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) for Amazon Elastic Container Service (Amazon ECS) tasks.
+ Use [IAM roles](shared-credentials-in-aws-powershell.md#shared-credentials-assume-role) for applications that are running on Amazon EC2 instances.

**Topics**
+ [Important warnings and guidelines](#pstools-creds-warnings-and-guidelines)
+ [AWS Credentials](specifying-your-aws-credentials.md)
+ [Shared Credentials](shared-credentials-in-aws-powershell.md)

# Using AWS Credentials
<a name="specifying-your-aws-credentials"></a>

Each AWS Tools for PowerShell command must include a set of AWS credentials, which are used to cryptographically sign the corresponding web service request. You can specify credentials per command, per session, or for all sessions. 

**Warning**  
To avoid security risks, don't use IAM users for authentication when developing purpose-built software or working with real data. Instead, use federation with an identity provider such as [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

**Note**  
The information in this topic is for circumstances where you need to obtain and manage short-term or long-term credentials manually. For additional information about short-term and long-term credentials, see [Other ways to authenticate](https://docs.aws.amazon.com/sdkref/latest/guide/access-users.html) in the *AWS SDKs and Tools Reference Guide*.  
For best security practices, use AWS IAM Identity Center, as described in [Authenticating with AWS](creds-idc.md).

As a best practice, to avoid exposing your credentials, do not put literal credentials in a command. Instead, create a profile for each set of credentials that you want to use, and store the profile in either of two credential stores. Specify the correct profile by name in your command, and the AWS Tools for PowerShell retrieves the associated credentials. For a general discussion of how to safely manage AWS credentials, see [Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) in the *Amazon Web Services General Reference*.

**Note**  
You need an AWS account to get credentials and use the AWS Tools for PowerShell. To create an AWS account, see [Getting started: Are you a first-time AWS user?](https://docs.aws.amazon.com/accounts/latest/reference/welcome-first-time-user.html) in the *AWS Account Management Reference Guide*.

**Topics**
+ [

## Credentials Store Locations
](#specifying-your-aws-credentials-store)
+ [

## Managing Profiles
](#managing-profiles)
+ [

## Specifying Credentials
](#specifying-your-aws-credentials-use)
+ [

## Credentials Search Order
](#pstools-cred-provider-chain-legacy)
+ [

## Credential Handling in AWS Tools for PowerShell Core
](#credential-handling-in-aws-tools-for-powershell-core)

## Credentials Store Locations
<a name="specifying-your-aws-credentials-store"></a>

The AWS Tools for PowerShell can use either of two credentials stores:
+ The AWS SDK store, which encrypts your credentials and stores them in your home folder. In Windows, this store is located at: `C:\Users\username\AppData\Local\AWSToolkit\RegisteredAccounts.json`.

  The [AWS SDK for .NET](https://aws.amazon.com/sdk-for-net/) and [Toolkit for Visual Studio](https://aws.amazon.com/visualstudio/) can also use the AWS SDK store.
+ The shared credentials file, which is also located in your home folder, but stores credentials as plain text.

  By default, the credentials file is stored here:
  + On Windows: `C:\Users\username\.aws\credentials`
  + On Mac/Linux: `~/.aws/credentials` 

  The AWS SDKs and the AWS Command Line Interface can also use the credentials file. If you're running a script outside of your AWS user context, be sure that the file that contains your credentials is copied to a location where all user accounts (local system and user) can access your credentials.

## Managing Profiles
<a name="managing-profiles"></a>

Profiles enable you to reference different sets of credentials with AWS Tools for PowerShell. You can use AWS Tools for PowerShell cmdlets to manage your profiles in the AWS SDK store. You can also manage profiles in the AWS SDK store by using the [Toolkit for Visual Studio](https://docs.aws.amazon.com/AWSToolkitVS/latest/UserGuide/tkv_setup.html) or programmatically by using the [AWS SDK for .NET](https://aws.amazon.com/sdk-for-net/). For directions about how to manage profiles in the credentials file, see [Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html).

### Add a New profile
<a name="add-a-new-profile"></a>

To add a new profile to the AWS SDK store, run the command `Set-AWSCredential`. It stores your access key and secret key in your default credentials file under the profile name you specify.

```
PS > Set-AWSCredential `
                 -AccessKey AKIA0123456787EXAMPLE `
                 -SecretKey wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY `
                 -StoreAs MyNewProfile
```
+  `-AccessKey`– The access key ID.
+  `-SecretKey`– The secret key.
+  `-StoreAs`– The profile name, which must be unique. To specify the default profile, use the name `default`.

### Update a Profile
<a name="update-a-profile"></a>

The AWS SDK store must be maintained manually. If you later change credentials on the service—for example, by using the [IAM console](https://console.aws.amazon.com/iam/home)—running a command with the locally stored credentials fails with the following error message:

```
The Access Key Id you provided does not exist in our records.
```

You can update a profile by repeating the `Set-AWSCredential` command for the profile, and passing it the new access and secret keys.

### List Profiles
<a name="list-profiles"></a>

You can check the current list of names with the following command. In this example, a user named Shirley has access to three profiles that are all stored in the shared credentials file (`~/.aws/credentials`).

```
PS > Get-AWSCredential -ListProfileDetail

ProfileName  StoreTypeName         ProfileLocation
-----------  -------------         ---------------
default      SharedCredentialsFile /Users/shirley/.aws/credentials
production   SharedCredentialsFile /Users/shirley/.aws/credentials
test         SharedCredentialsFile /Users/shirley/.aws/credentials
```

### Remove a Profile
<a name="remove-a-profile"></a>

To remove a profile that you no longer require, use the following command.

```
PS > Remove-AWSCredentialProfile -ProfileName an-old-profile-I-do-not-need
```

The `-ProfileName` parameter specifies the profile that you want to delete.

The deprecated command [Clear-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Clear-AWSCredential.html) is still available for backward compatibility, but `Remove-AWSCredentialProfile` is preferred.

## Specifying Credentials
<a name="specifying-your-aws-credentials-use"></a>

There are several ways to specify credentials. The preferred way is to identify a profile instead of incorporating literal credentials into your command line. AWS Tools for PowerShell locates the profile using a search order that is described in [Credentials Search Order](#pstools-cred-provider-chain-legacy).

On Windows, AWS credentials stored in the AWS SDK store are encrypted with the logged-in Windows user identity. They cannot be decrypted by using another account, or used on a device that's different from the one on which they were originally created. To perform tasks that require the credentials of another user, such as a user account under which a scheduled task will run, set up a credential profile, as described in the preceding section, that you can use when you log in to the computer as that user. Log in as the task-performing user to complete the credential setup steps, and create a profile that works for that user. Then log out and log in again with your own credentials to set up the scheduled task.

**Note**  
Use the `-ProfileName` common parameter to specify a profile. This parameter is equivalent to the `-StoredCredentials` parameter in earlier AWS Tools for PowerShell releases. For backward compatibility, `-StoredCredentials` is still supported.

### Default Profile (Recommended)
<a name="default-profile-recommended"></a>

All AWS SDKs and management tools can find your credentials automatically on your local computer if the credentials are stored in a profile named `default`. For example, if you have a profile named `default` on the local computer, you don't have to run either the `Initialize-AWSDefaultConfiguration` cmdlet or the `Set-AWSCredential` cmdlet. The tools automatically use the access and secret key data stored in that profile. To use an AWS Region other than your default Region (the results of `Get-DefaultAWSRegion`), you can run `Set-DefaultAWSRegion` and specify a Region.

If your profile is not named `default`, but you want to use it as the default profile for the current session, run `Set-AWSCredential` to set it as the default profile.

Although running `Initialize-AWSDefaultConfiguration` lets you specify a default profile for every PowerShell session, the cmdlet loads credentials from your custom-named profile, but overwrites the `default` profile with the named profile.

We recommend that you do not run `Initialize-AWSDefaultConfiguration` unless you are running a PowerShell session on an Amazon EC2 instance that was not launched with an instance profile, and you want to set up the credential profile manually. Note that the credential profile in this scenario would not contain credentials. The credential profile that results from running `Initialize-AWSDefaultConfiguration` on an EC2 instance doesn't directly store credentials, but instead points to instance metadata (that provides temporary credentials that automatically rotate). However, it does store the instance's Region. Another scenario that might require running `Initialize-AWSDefaultConfiguration` occurs if you want to run a call against a Region other than the Region in which the instance is running. Running that command permanently overrides the Region stored in the instance metadata.

```
PS > Initialize-AWSDefaultConfiguration -ProfileName MyProfileName -Region us-west-2
```

**Note**  
The default credentials are included in the AWS SDK store under the `default` profile name. The command overwrites any existing profile with that name.

If your EC2 instance was launched with an instance profile, PowerShell automatically gets the AWS credentials and Region information from the instance profile. You don't need to run `Initialize-AWSDefaultConfiguration`. Running the `Initialize-AWSDefaultConfiguration` cmdlet on an EC2 instance launched with an instance profile isn't necessary, because it uses the same instance profile data that PowerShell already uses by default.

### Session Profile
<a name="session-profile"></a>

Use `Set-AWSCredential` to specify a default profile for a particular session. This profile overrides any default profile for the duration of the session. We recommend this if you want to use a custom-named profile in your session instead of the current `default` profile.

```
PS > Set-AWSCredential -ProfileName MyProfileName
```

**Note**  
In versions of the Tools for Windows PowerShell that are earlier than 1.1, the `Set-AWSCredential` cmdlet did not work correctly, and would overwrite the profile specified by "MyProfileName". We recommend using a more recent version of the Tools for Windows PowerShell.

### Command Profile
<a name="command-profile"></a>

On individual commands, you can add the `-ProfileName` parameter to specify a profile that applies to only that one command. This profile overrides any default or session profiles, as shown in the following example.

```
PS > Get-EC2Instance -ProfileName MyProfileName
```

**Note**  
When you specify a default or session profile, you can also add a `-Region` parameter to override a default or session Region. For more information, see [Specify the AWS Region for the AWS Tools for PowerShell](pstools-installing-specifying-region.md). The following example specifies a default profile and Region.  

```
PS > Initialize-AWSDefaultConfiguration -ProfileName MyProfileName -Region us-west-2
```

By default, the AWS shared credentials file is assumed to be in the user's home folder (`C:\Users\username\.aws` on Windows, or `~/.aws` on Linux). To specify a credentials file in a different location, include the `-ProfileLocation` parameter and specify the credentials file path. The following example specifies a non-default credentials file for a specific command.

```
PS > Get-EC2Instance -ProfileName MyProfileName -ProfileLocation C:\aws_service_credentials\credentials
```

**Note**  
If you are running a PowerShell script during a time that you are not normally signed in to AWS—for example, you are running a PowerShell script as a scheduled task outside of your normal work hours—add the `-ProfileLocation` parameter when you specify the profile that you want to use, and set the value to the path of the file that stores your credentials. To be certain that your AWS Tools for PowerShell script runs with the correct account credentials, you should add the `-ProfileLocation` parameter whenever your script runs in a context or process that does not use an AWS account. You can also copy your credentials file to a location that is accessible to the local system or other account that your scripts use to perform tasks.

## Credentials Search Order
<a name="pstools-cred-provider-chain-legacy"></a>

When you run a command, AWS Tools for PowerShell searches for credentials in the following order. It stops when it finds usable credentials.

1. Literal credentials that are embedded as parameters in the command line.

   We strongly recommend using profiles instead of putting literal credentials in your command lines.

1. Credentials specified by the `-Credential` parameter.

1. A profile name or profile location that was specified by using the [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html) cmdlet.
   + If you specify only a profile name, the command looks for the specified profile in the AWS SDK store and, if that does not exist, the specified profile from the AWS shared credentials file in the default location.
   + If you specify only a profile location, the command looks for the `default` profile from that credentials file.
   + If you specify both a name and a location, the command looks for the specified profile in that credentials file.

   If the specified profile or location is not found, the command throws an exception. Search proceeds to the following steps only if you did not specify a profile or location.

1. Credentials that are created from the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables, if all three variables have a value.

1. The credentials profile with the name specified by the `AWS_PROFILE` environment variable.

1. The default profile, in the following order:

   1. The `default` profile in the AWS SDK store.

   1. The `default` profile in the shared AWS `credentials` file.

   1. The `AWS PS Default` profile in the AWS SDK store.

1. If the command is running on an Amazon EC2 instance that is configured to use an IAM role, the EC2 instance's temporary credentials accessed from the instance profile.

   For more information about using IAM roles for Amazon EC2 instances, see [Granting access with a role](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-hosm.html) in the [AWS SDK for .NET Developer Guide](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/).

If this search fails to locate the specified credentials, the command throws an exception.

For additional information about environment variables and credentials profiles, see the following topics in the [AWS SDKs and Tools Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/): [Environment variables](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html), [Environment variables list](https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html#EVarSettings), and [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html).

## Credential Handling in AWS Tools for PowerShell Core
<a name="credential-handling-in-aws-tools-for-powershell-core"></a>

Cmdlets in AWS Tools for PowerShell Core accept AWS access and secret keys or the names of credential profiles when they run, similarly to the AWS Tools for Windows PowerShell. When they run on Windows, both modules have access to the AWS SDK for .NET credential store file (stored in the per-user `AppData\Local\AWSToolkit\RegisteredAccounts.json` file). 

This file stores your keys in encrypted format, and cannot be used on a different computer. It is the first file that the AWS Tools for PowerShell searches for a credential profile, and is also the file where the AWS Tools for PowerShell stores credential profiles. For more information about the AWS SDK for .NET credential store file, see [Configuring AWS Credentials](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-creds.html). The Tools for Windows PowerShell module does not currently support writing credentials to other files or locations.

Both modules can read profiles from the AWS shared credentials file that is used by other AWS SDKs and the AWS CLI. On Windows, the default location for this file is `C:\Users\<userid>\.aws\credentials`. On non-Windows platforms, this file is stored at `~/.aws/credentials`. The `-ProfileLocation` parameter can be used to point to a non-default file name or file location.

The SDK credential store holds your credentials in encrypted form by using Windows cryptographic APIs. These APIs are not available on other platforms, so the AWS Tools for PowerShell Core module uses the AWS shared credentials file exclusively, and supports writing new credential profiles to the shared credential file.

The following example scripts that use the `Set-AWSCredential` cmdlet show the options for handling credential profiles on Windows with either the **AWSPowerShell** or **AWSPowerShell.NetCore** modules.

```
# Writes a new (or updates existing) profile with name "myProfileName"
# in the encrypted SDK store file

Set-AWSCredential -AccessKey akey -SecretKey skey -StoreAs myProfileName

# Checks the encrypted SDK credential store for the profile and then
# falls back to the shared credentials file in the default location

Set-AWSCredential -ProfileName myProfileName

# Bypasses the encrypted SDK credential store and attempts to load the
# profile from the ini-format credentials file "mycredentials" in the
# folder C:\MyCustomPath

Set-AWSCredential -ProfileName myProfileName -ProfileLocation C:\MyCustomPath\mycredentials
```

The following examples show the behavior of the **AWSPowerShell.NetCore** module on the Linux or macOS operating systems.

```
# Writes a new (or updates existing) profile with name "myProfileName"
# in the default shared credentials file ~/.aws/credentials

Set-AWSCredential -AccessKey akey -SecretKey skey -StoreAs myProfileName

# Writes a new (or updates existing) profile with name "myProfileName"
# into an ini-format credentials file "~/mycustompath/mycredentials"

Set-AWSCredential -AccessKey akey -SecretKey skey -StoreAs myProfileName -ProfileLocation ~/mycustompath/mycredentials

# Reads the default shared credential file looking for the profile "myProfileName"

Set-AWSCredential -ProfileName myProfileName

# Reads the specified credential file looking for the profile "myProfileName"

Set-AWSCredential -ProfileName myProfileName -ProfileLocation ~/mycustompath/mycredentials
```

# Shared Credentials in AWS Tools for PowerShell
<a name="shared-credentials-in-aws-powershell"></a>

The Tools for Windows PowerShell support the use of the AWS shared credentials file, similarly to the AWS CLI and other AWS SDKs. The Tools for Windows PowerShell now support reading and writing of `basic`, `session`, and `assume role` credential profiles to both the .NET credentials file and the AWS shared credential file. This functionality is enabled by a new `Amazon.Runtime.CredentialManagement` namespace.

**Warning**  
To avoid security risks, don't use IAM users for authentication when developing purpose-built software or working with real data. Instead, use federation with an identity provider such as [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

**Note**  
The information in this topic is for circumstances where you need to obtain and manage short-term or long-term credentials manually. For additional information about short-term and long-term credentials, see [Other ways to authenticate](https://docs.aws.amazon.com/sdkref/latest/guide/access-users.html) in the *AWS SDKs and Tools Reference Guide*.  
For best security practices, use AWS IAM Identity Center, as described in [Authenticating with AWS](creds-idc.md).

The new profile types and access to the AWS shared credential file are supported by the following parameters that have been added to the credentials-related cmdlets, [Initialize-AWSDefaultConfiguration](https://docs.aws.amazon.com/powershell/v5/reference/items/Initialize-AWSDefaultConfiguration.html), [New-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/New-AWSCredential.html), and [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html). In service cmdlets, you can refer to your profiles by adding the common parameter, `-ProfileName`.

## Using an IAM Role with AWS Tools for PowerShell
<a name="shared-credentials-assume-role"></a>

The AWS shared credential file enables additional types of access. For example, you can access your AWS resources by using an IAM role instead of the long term credentials of an IAM user. To do this, you must have a standard profile that has permissions to assume the role. When you tell the AWS Tools for PowerShell to use a profile that specified a role, the AWS Tools for PowerShell looks up the profile identified by the `SourceProfile` parameter. Those credentials are used to request temporary credentials for the role specified by the `RoleArn` parameter. You can optionally require the use of an multi-factor authentication (MFA) device or an `ExternalId` code when the role is assumed by a third party.


****  

| Parameter Name | Description | 
| --- | --- | 
|  ExternalId  |  The user-defined external ID to be used when assuming a role, if required by the role. This is typically only required when you delegate access to your account to a third party. The third party must include the ExternalId as a parameter when assuming the assigned role. For more information, see [How to Use an External ID When Granting Access to Your AWS Resources to a Third Party](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) in the *IAM User Guide*.  | 
|  MfaSerial  |  The MFA serial number to be used when assuming a role, if required by the role. For more information, see [Using Multi-Factor Authentication (MFA) in AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html) in the *IAM User Guide*.  | 
|  RoleArn  |  The ARN of the role to assume for assume role credentials. For more information about creating and using roles, see [IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *IAM User Guide*.  | 
|  SourceProfile  |  The name of the source profile to be used by assume role credentials. The credentials found in this profile are used to assume the role specified by the `RoleArn` parameter.  | 

### Setup of profiles for assuming a role
<a name="setup"></a>

The following is an example showing how to set up a source profile that enables directly assuming an IAM role. 

The first command creates a source profile that is referenced by the role profile. The second command creates the role profile that which role to assume. The third command shows the credentials for the role profile.

```
PS > Set-AWSCredential -StoreAs my_source_profile -AccessKey access_key_id -SecretKey secret_key
PS > Set-AWSCredential -StoreAs my_role_profile -SourceProfile my_source_profile -RoleArn arn:aws:iam::123456789012:role/role-i-want-to-assume
PS > Get-AWSCredential -ProfileName my_role_profile

SourceCredentials                  RoleArn                                              RoleSessionName                           Options
-----------------                  -------                                              ---------------                           -------
Amazon.Runtime.BasicAWSCredentials arn:aws:iam::123456789012:role/role-i-want-to-assume aws-dotnet-sdk-session-636238288466144357 Amazon.Runtime.AssumeRoleAWSCredentialsOptions
```

To use this role profile with the Tools for Windows PowerShell service cmdlets, add the `-ProfileName` common parameter to the command to reference the role profile. The following example uses the role profile defined in the previous example to access the [Get-S3Bucket](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-S3Bucket.html) cmdlet. AWS Tools for PowerShell looks up the credentials in `my_source_profile`, uses those credentials to call `AssumeRole` on behalf of the user, and then uses those temporary role credentials to call `Get-S3Bucket`.

```
PS > Get-S3Bucket -ProfileName my_role_profile

CreationDate           BucketName
------------           ----------
2/27/2017 8:57:53 AM   4ba3578c-f88f-4d8b-b95f-92a8858dac58-bucket1
2/27/2017 10:44:37 AM  2091a504-66a9-4d69-8981-aaef812a02c3-bucket2
```

## Using the Credential Profile Types
<a name="using-the-credential-profile-types"></a>

To set a credential profile type, understand which parameters provide the information required by the profile type.


****  

| Credentials Type | Parameters you must use | 
| --- | --- | 
|  **Basic** These are the long term credentials for an IAM user  |  `-AccessKey`  `-SecretKey`  | 
|  **Session**: These are the short term credentials for an IAM role that you retrieve manually, such as by directly calling the [Use-STSRole](https://docs.aws.amazon.com/powershell/v5/reference/items/Use-STSRole.html) cmdlet.  |  `-AccessKey`  `-SecretKey` `-SessionToken`  | 
|  **Role**: These are are short term credentials for an IAM role that AWS Tools for PowerShell retrieve for you.  |  `-SourceProfile` `-RoleArn`  optional: `-ExternalId` optional: `-MfaSerial`  | 

## The `ProfileLocation` Common Parameter
<a name="the-profileslocation-common-parameter"></a>

You can use `-ProfileLocation` to write to the shared credential file as well as instruct a cmdlet to read from the credential file. Adding the `-ProfileLocation` parameter controls whether Tools for Windows PowerShell uses the shared credential file or the .NET credential file. The following table describes how the parameter works in Tools for Windows PowerShell.


****  

| Profile Location Value | Profile Resolution Behavior | 
| --- | --- | 
|  null (not set) or empty  |  First, search the .NET credential file for a profile with the specified name. If the profile isn't found, search the AWS shared credentials file at `(user's home directory)\.aws\credentials`.  | 
|  The path to a file in the AWS shared credential file format  |  Search only the specified file for a profile with the given name.  | 

### Save Credentials to a Credentials File
<a name="save-credentials-to-a-credentials-file"></a>

To write and save credentials to one of the two credential files, run the `Set-AWSCredential` cmdlet. The following example shows how to do this. The first command uses `Set-AWSCredential` with `-ProfileLocation` to add access and secret keys to a profile specified by the `-ProfileName` parameter. In the second line, run the [Get-Content](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content) cmdlet to display the contents of the credentials file.

```
PS > Set-AWSCredential -ProfileLocation C:\Users\auser\.aws\credentials -ProfileName basic_profile -AccessKey access_key2 -SecretKey secret_key2
PS > Get-Content C:\Users\auser\.aws\credentials

aws_access_key_id=access_key2
aws_secret_access_key=secret_key2
```

## Displaying Your Credential Profiles
<a name="showing-credential-profiles"></a>

Run the [Get-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-AWSCredential.html) cmdlet and add the `-ListProfileDetail` parameter to return credential file types and locations, and a list of profile names.

```
PS > Get-AWSCredential -ListProfileDetail

ProfileName                     StoreTypeName         ProfileLocation
-----------                     -------------         ---------------
source_profile                  NetSDKCredentialsFile
assume_role_profile             NetSDKCredentialsFile
basic_profile                   SharedCredentialsFile C:\Users\auser\.aws\credentials
```

## Removing Credential Profiles
<a name="removing-credential-profiles"></a>

To remove credential profiles, run the new [Remove-AWSCredentialProfile](https://docs.aws.amazon.com/powershell/v5/reference/items/Remove-AWSCredentialProfile.html) cmdlet. [Clear-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Clear-AWSCredential.html) is deprecated, but still available for backward compatibility.

## Important Notes
<a name="important-notes"></a>

Only [Initialize-AWSDefaultConfiguration](https://docs.aws.amazon.com/powershell/v5/reference/items/Initialize-AWSDefaultConfiguration.html), [New-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/New-AWSCredential.html), and [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html) support the parameters for role profiles. You cannot specify the role parameters directly on a command such as `Get-S3Bucket -SourceProfile source_profile_name -RoleArn arn:aws:iam::999999999999:role/role_name`. That does not work because service cmdlets do not directly support the `SourceProfile` or `RoleArn` parameters. Instead, you must store those parameters in a profile, then call the command with the `-ProfileName` parameter.