

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)

# Calling AWS services in the AWS Tools for PowerShell
<a name="pstools-using"></a>

This section provides examples of using the AWS Tools for PowerShell to access AWS services. These examples help demonstrate how to use the cmdlets to perform actual AWS tasks. These examples rely on cmdlets that the Tools for PowerShell provides. To see what cmdlets are available, see the [AWS Tools for PowerShell Cmdlet Reference](https://docs.aws.amazon.com/powershell/v5/reference/).

You can find more AWS Tools for PowerShell examples in the [Code examples](powershell_code_examples.md) chapter.

## PowerShell File Concatenation Encoding
<a name="powershell-file-concatenation-encoding"></a>

Some cmdlets in the AWS Tools for PowerShell edit existing files or records that you have in AWS. An example is `Edit-R53ResourceRecordSet`, which calls the [ChangeResourceRecordSets](https://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html) API for Amazon Route 53.

When you edit or concatenate files in PowerShell 5.1 or older releases, PowerShell encodes the output in UTF-16, not UTF-8. This can add unwanted characters and create results that are not valid. A hexadecimal editor can reveal the unwanted characters.

To avoid converting file output to UTF-16, you can pipe your command into PowerShell's `Out-File` cmdlet and specify UTF-8 encoding, as shown in the following example:

```
PS > *some file concatenation command* | Out-File filename.txt -Encoding utf8
```

If you are running AWS CLI commands from within the PowerShell console, the same behavior applies. You can pipe the output of an AWS CLI command into `Out-File` in the PowerShell console. Other cmdlets, such as `Export-Csv` or `Export-Clixml`, also have an `Encoding` parameter. For a complete list of cmdlets that have an `Encoding` parameter, and that allow you to correct the encoding of the output of a concatenated file, run the following command:

```
PS > Get-Command -ParameterName "Encoding"
```

**Note**  
PowerShell 6.0 and newer, including PowerShell Core, automatically retains UTF-8 encoding for concatenated file output.

## Returned Objects for the PowerShell Tools
<a name="returned-objects-for-the-powershell-tools"></a>

To make AWS Tools for PowerShell more useful in a native PowerShell environment, the object returned by a AWS Tools for PowerShell cmdlet is a .NET object, not the JSON text object that is typically returned from the corresponding API in the AWS SDK. For example, `Get-S3Bucket` emits a `Buckets` collection, not an Amazon S3 JSON response object. The `Buckets` collection can be placed in the PowerShell pipeline and interacted with in appropriate ways. Similarly, `Get-EC2Instance` emits a `Reservation` .NET object collection, not a `DescribeEC2Instances` JSON result object. This behavior is by design and enables the AWS Tools for PowerShell experience to be more consistent with idiomatic PowerShell.

The actual service responses are available for you if you need them. They are stored as `note` properties on the returned objects. For API actions that support paging by using `NextToken` fields, these are also attached as `note` properties.

## [Amazon EC2](pstools-ec2.md)
<a name="using-ec2"></a>

This section walks through the steps required to launch an Amazon EC2 instance including how to:
+ Retrieve a list of Amazon Machine Images (AMIs).
+ Create a key pair for SSH authentication.
+ Create and configure an Amazon EC2 security group.
+ Launch the instance and retrieve information about it.

## [Amazon S3](pstools-s3.md)
<a name="using-s3"></a>

The section walks through the steps required to create a static website hosted in Amazon S3. It demonstrates how to:
+ Create and delete Amazon S3 buckets.
+ Upload files to an Amazon S3 bucket as objects.
+ Delete objects from an Amazon S3 bucket.
+ Designate an Amazon S3 bucket as a website.

## [AWS Lambda and AWS Tools for PowerShell](pstools-lambda.md)
<a name="using-lambda"></a>

This section provides a brief overview of the AWS Lambda Tools for PowerShell module and describes the required steps for setting up the module.

## [Amazon SNS and Amazon SQS](pstools-sqs-queue-sns-topic.md)
<a name="using-sns"></a>

This section walks through the steps required to subscribe an Amazon SQS queue to an Amazon SNS topic. It demonstrates how to:
+ Create an Amazon SNS topic.
+ Create an Amazon SQS queue.
+ Subscribe the queue to the topic.
+ Send a message to the topic.
+ Receive the message from the queue.

## [CloudWatch](pstools-cw.md)
<a name="using-cw"></a>

This section provides an example of how to publish custom data to CloudWatch.
+ Publish a Custom Metric to Your CloudWatch Dashboard.

## See Also
<a name="see-also"></a>
+  [Configuring and using the AWS Tools for PowerShell](pstools-getting-started.md) 

## Topics
<a name="w2aac13c23"></a>
+ [Amazon S3 and Tools for Windows PowerShell](pstools-s3.md)
+ [Amazon EC2 and Tools for Windows PowerShell](pstools-ec2.md)
+ [AWS Lambda and AWS Tools for PowerShell](pstools-lambda.md)
+ [Amazon SQS, Amazon SNS and Tools for Windows PowerShell](pstools-sqs-queue-sns-topic.md)
+ [CloudWatch from the AWS Tools for Windows PowerShell](pstools-cw.md)
+ [Using the ClientConfig parameter in cmdlets](pstools-clientconfig.md)

# Amazon S3 and Tools for Windows PowerShell
<a name="pstools-s3"></a>

In this section, we create a static website using the AWS Tools for Windows PowerShell using Amazon S3 and CloudFront. In the process, we demonstrate a number of common tasks with these services. This walkthrough is modeled after the Getting Started Guide for [Host a Static Website](https://aws.amazon.com/getting-started/projects/host-static-website/), which describes a similar process using the [AWS Management Console](https://console.aws.amazon.com/s3/home).

The commands shown here assume that you have set default credentials and a default region for your PowerShell session. Therefore, credentials and regions are not included in the invocation of the cmdlets.

**Note**  
There is currently no Amazon S3 API for renaming a bucket or object, and therefore, no single Tools for Windows PowerShell cmdlet for performing this task. To rename an object in S3, we recommend that you copy the object to one with a new name, by running the [Copy-S3Object](https://docs.aws.amazon.com/powershell/v5/reference/items/Copy-S3Object.html) cmdlet, and then delete the original object by running the [Remove-S3Object](https://docs.aws.amazon.com/powershell/v5/reference/items/Remove-S3Object.html) cmdlet.

**See also**
+  [Calling AWS services in the AWS Tools for PowerShell](pstools-using.md) 
+  [Hosting a Static Website on Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) 
+  [Amazon S3 Console](https://console.aws.amazon.com/s3/home) 

**Topics**
+ [

# Create an Amazon S3 Bucket, Verify Its Region, and Optionally Remove It
](pstools-s3-bucket-create.md)
+ [

# Configure an Amazon S3 Bucket as a Website and Enable Logging
](pstools-s3-create-website.md)
+ [

# Upload Objects to an Amazon S3 Bucket
](pstools-s3-upload-object.md)
+ [

# Delete Amazon S3 Objects and Buckets
](pstools-s3-delete-website.md)
+ [

# Upload In-Line Text Content to Amazon S3
](pstools-s3-upload-in-line-text.md)

# Create an Amazon S3 Bucket, Verify Its Region, and Optionally Remove It
<a name="pstools-s3-bucket-create"></a>

Use the `New-S3Bucket` cmdlet to create a new Amazon S3 bucket. The following examples creates a bucket named `website-example`. The name of the bucket must be unique across all regions. The example creates the bucket in the `us-west-1` region.

```
PS > New-S3Bucket -BucketName website-example -Region us-west-2

CreationDate         BucketName
------------         ----------
8/16/19 8:45:38 PM   website-example
```

You can verify the region in which the bucket is located using the `Get-S3BucketLocation` cmdlet.

```
PS > Get-S3BucketLocation -BucketName website-example

Value
-----
us-west-2
```

When you're done with this tutorial, you can use the following line to remove this bucket. We suggest that you leave this bucket in place as we use it in subsequent examples.

```
PS > Remove-S3Bucket -BucketName website-example
```

Note that the bucket removal process can take some time to finish. If you try to re-create a same-named bucket immediately, the `New-S3Bucket` cmdlet can fail until the old one is completely gone.

## See Also
<a name="pstools-seealso-s3-bucket-create"></a>
+  [Calling AWS services in the AWS Tools for PowerShell](pstools-using.md) 
+  [Put Bucket (Amazon S3 Service Reference)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html) 
+  [AWS PowerShell Regions for Amazon S3](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) 

# Configure an Amazon S3 Bucket as a Website and Enable Logging
<a name="pstools-s3-create-website"></a>

Use the `Write-S3BucketWebsite` cmdlet to configure an Amazon S3 bucket as a static website. The following example specifies a name of `index.html` for the default content web page and a name of `error.html` for the default error web page. Note that this cmdlet does not create those pages. They need to be [uploaded as Amazon S3 objects](pstools-s3-upload-object.md).

```
PS > Write-S3BucketWebsite -BucketName website-example -WebsiteConfiguration_IndexDocumentSuffix index.html -WebsiteConfiguration_ErrorDocument error.html
RequestId      : A1813E27995FFDDD
AmazonId2      : T7hlDOeLqA5Q2XfTe8j2q3SLoP3/5XwhUU3RyJBGHU/LnC+CIWLeGgP0MY24xAlI
ResponseStream :
Headers        : {x-amz-id-2, x-amz-request-id, Content-Length, Date...}
Metadata       : {}
ResponseXml    :
```

## See Also
<a name="pstools-seealso-s3-create-website"></a>
+  [Calling AWS services in the AWS Tools for PowerShell](pstools-using.md) 
+  [Put Bucket Website (Amazon S3 API Reference)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html) 
+  [Put Bucket ACL (Amazon S3 API Reference)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html) 

# Upload Objects to an Amazon S3 Bucket
<a name="pstools-s3-upload-object"></a>

Use the `Write-S3Object` cmdlet to upload files from your local file system to an Amazon S3 bucket as objects. The example below creates and uploads two simple HTML files to an Amazon S3 bucket, and verifies the existence of the uploaded objects. The `-File` parameter to `Write-S3Object` specifies the name of the file in the local file system. The `-Key` parameter specifies the name that the corresponding object will have in Amazon S3.

Amazon infers the content-type of the objects from the file extensions, in this case, ".html".

```
PS > # Create the two files using here-strings and the Set-Content cmdlet
PS > $index_html = @"
>> <html>
>>   <body>
>>     <p>
>>       Hello, World!
>>     </p>
>>   </body>
>> </html>
>> "@
>>
PS > $index_html | Set-Content index.html
PS > $error_html = @"
>> <html>
>>   <body>
>>     <p>
>>       This is an error page.
>>     </p>
>>   </body>
>> </html>
>> "@
>>
>>$error_html | Set-Content error.html
>># Upload the files to Amazon S3 using a foreach loop
>>foreach ($f in "index.html", "error.html") {
>> Write-S3Object -BucketName website-example -File $f -Key $f -CannedACLName public-read
>> }
>>
PS > # Verify that the files were uploaded
PS > Get-S3BucketWebsite -BucketName website-example

IndexDocumentSuffix                                         ErrorDocument
-------------------                                         -------------
index.html                                                  error.html
```

 *Canned ACL Options* 

The values for specifying canned ACLs with the Tools for Windows PowerShell are the same as those used by the AWS SDK for .NET. Note, however, that these are different from the values used by the Amazon S3`Put Object` action. The Tools for Windows PowerShell support the following canned ACLs:
+ NoACL
+ private
+ public-read
+ public-read-write
+ aws-exec-read
+ authenticated-read
+ bucket-owner-read
+ bucket-owner-full-control
+ log-delivery-write

For more information about these canned ACL settings, see [Access Control List Overview](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl).

## Note Regarding Multipart Upload
<a name="note-regarding-multipart-upload"></a>

If you use the Amazon S3 API to upload a file that is larger than 5 GB in size, you need to use multipart upload. However, the `Write-S3Object` cmdlet provided by the Tools for Windows PowerShell can transparently handle file uploads that are greater than 5 GB.

### Test the Website
<a name="pstools-amazon-s3-test-website"></a>

At this point, you can test the website by navigating to it using a browser. URLs for static websites hosted in Amazon S3 follow a standard format.

```
http://<bucket-name>.s3-website-<region>.amazonaws.com
```

For example:

```
http://website-example.s3-website-us-west-1.amazonaws.com
```

### See Also
<a name="pstools-seealso-amazon-s3-test-website"></a>
+  [Calling AWS services in the AWS Tools for PowerShell](pstools-using.md) 
+  [Put Object (Amazon S3 API Reference)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html) 
+  [Canned ACLs (Amazon S3 API Reference)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ACLOverview.html#CannedACL) 

# Delete Amazon S3 Objects and Buckets
<a name="pstools-s3-delete-website"></a>

This section describes how to delete the website that you created in preceding sections. You can simply delete the objects for the HTML files, and then delete the Amazon S3 bucket for the site.

First, run the `Remove-S3Object` cmdlet to delete the objects for the HTML files from the Amazon S3 bucket.

```
PS > foreach ( $obj in "index.html", "error.html" ) {
>> Remove-S3Object -BucketName website-example -Key $obj
>> }
>> 
IsDeleteMarker
--------------
False
```

The `False` response is an expected artifact of the way that Amazon S3 processes the request. In this context, it does not indicate an issue.

Now you can run the `Remove-S3Bucket` cmdlet to delete the now-empty Amazon S3 bucket for the site.

```
PS > Remove-S3Bucket -BucketName website-example

RequestId      : E480ED92A2EC703D
AmazonId2      : k6tqaqC1nMkoeYwbuJXUx1/UDa49BJd6dfLN0Ls1mWYNPHjbc8/Nyvm6AGbWcc2P
ResponseStream :
Headers        : {x-amz-id-2, x-amz-request-id, Date, Server}
Metadata       : {}
ResponseXml    :
```

In 1.1 and newer versions of the AWS Tools for PowerShell, you can add the `-DeleteBucketContent` parameter to `Remove-S3Bucket`, which first deletes all objects and object versions in the specified bucket before trying to remove the bucket itself. Depending on the number of objects or object versions in the bucket, this operation can take a substantial amount of time. In versions of the Tools for Windows PowerShell older than 1.1, the bucket had to be empty before `Remove-S3Bucket` could delete it.

**Note**  
Unless you add the `-Force` parameter, AWS Tools for PowerShell prompts you for confirmation before the cmdlet runs.

## See Also
<a name="pstools-seealso-amazon-s3-delete-website"></a>
+  [Calling AWS services in the AWS Tools for PowerShell](pstools-using.md) 
+  [Delete Object (Amazon S3 API Reference)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html) 
+  [DeleteBucket (Amazon S3 API Reference)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETE.html) 

# Upload In-Line Text Content to Amazon S3
<a name="pstools-s3-upload-in-line-text"></a>

The `Write-S3Object` cmdlet supports the ability to upload in-line text content to Amazon S3. Using the `-Content` parameter (alias `-Text`), you can specify text-based content that should be uploaded to Amazon S3 without needing to place it into a file first. The parameter accepts simple one-line strings as well as here strings that contain multiple lines.

```
PS > # Specifying content in-line, single line text:
PS > write-s3object amzn-s3-demo-bucket -key myobject.txt -content "file content"

PS > # Specifying content in-line, multi-line text: (note final newline needed to end in-line here-string)
PS > write-s3object amzn-s3-demo-bucket -key myobject.txt -content @"
>> line 1
>> line 2
>> line 3
>> "@
>> 
PS > # Specifying content from a variable: (note final newline needed to end in-line here-string)
PS > $x = @"
>> line 1
>> line 2
>> line 3
>> "@
>> 
PS > write-s3object amzn-s3-demo-bucket -key myobject.txt -content $x
```

# Amazon EC2 and Tools for Windows PowerShell
<a name="pstools-ec2"></a>

You can perform common tasks related to Amazon EC2 using the AWS Tools for PowerShell.

The example commands shown here assume that you have set default credentials and a default region for your PowerShell session. Therefore, we don't include credentials or region when we invoke the cmdlets. For more information, see [Authenticating with AWS](creds-idc.md) and [AWS Region](pstools-installing-specifying-region.md).

**Topics**
+ [Create a Key Pair](pstools-ec2-keypairs.md)
+ [Create a Security Group](pstools-ec2-sg.md)
+ [Find an AMI](pstools-ec2-get-amis.md)
+ [Launch an Instance](pstools-ec2-launch.md)

# Creating a Key Pair
<a name="pstools-ec2-keypairs"></a>

The following `New-EC2KeyPair` example creates a key pair and stores in the PowerShell variable `$myPSKeyPair` 

```
PS > $myPSKeyPair = New-EC2KeyPair -KeyName myPSKeyPair
```

Pipe the key pair object into the `Get-Member` cmdlet to see the object's structure.

```
PS > $myPSKeyPair | Get-Member

     TypeName: Amazon.EC2.Model.KeyPair

  Name                MemberType   Definition
  ----                ----------   ----------
  Equals              Method       bool Equals(System.Object obj)
  GetHashCode         Method       int GetHashCode()
  GetType             Method       type GetType()
  ToString            Method       string ToString()
  KeyFingerprint      Property     System.String KeyFingerprint {get;set;}
  KeyMaterial         Property     System.String KeyMaterial {get;set;}
  KeyName             Property     System.String KeyName {get;set;}
```

Pipe the key pair object into the `Format-List` cmdlet to view values of the `KeyName`, `KeyFingerprint`, and `KeyMaterial` members. (The output has been truncated for readability.)

```
PS > $myPSKeyPair | Format-List KeyName, KeyFingerprint, KeyMaterial

  KeyName        : myPSKeyPair
  KeyFingerprint : 09:06:70:8e:26:b6:e7:ef:8f:fe:4a:1d:bc:9c:6a:63:11:ac:ad:3c
  KeyMaterial    : ----BEGIN RSA PRIVATE KEY----
                   MIIEogIBAAKCAQEAkK+ANYUS9c7niNjYfaCn6KYj/D0I6djnFoQE...
                   Mz6btoxPcE7EMeH1wySUp8nouAS9xbl9l7+VkD74bN9KmNcPa/Mu...
                   Zyn4vVe0Q5il/MpkrRogHqOB0rigeTeV5Yc3lvO0RFFPu0Kz4kcm...
                   w3Jg8dKsWn0plOpX7V3sRC02KgJIbejQUvBFGi5OQK9bm4tXBIeC...
                   daxKIAQMtDUdmBDrhR1/YMv8itFe5DiLLbq7Ga+FDcS85NstBa3h...
                   iuskGkcvgWkcFQkLmRHRoDpPb+OdFsZtjHZDpMVFmA9tT8EdbkEF...
                   3SrNeqZPsxJJIxOodb3CxLJpg75JU5kyWnb0+sDNVHoJiZCULCr0...
                   GGlLfEgB95KjGIk7zEv2Q7K6s+DHclrDeMZWa7KFNRZuCuX7jssC...
                   xO98abxMr3o3TNU6p1ZYRJEQ0oJr0W+kc+/8SWb8NIwfLtwhmJEy...
                   1BX9X8WFX/A8VLHrT1elrKmLkNECgYEAwltkV1pOJAFhz9p7ZFEv...
                   vvVsPaF0Ev9bk9pqhx269PB5Ox2KokwCagDMMaYvasWobuLmNu/1...
                   lmwRx7KTeQ7W1J3OLgxHA1QNMkip9c4Tb3q9vVc3t/fPf8vwfJ8C...
                   63g6N6rk2FkHZX1E62BgbewUd3eZOS05Ip4VUdvtGcuc8/qa+e5C...
                   KXgyt9nl64pMv+VaXfXkZhdLAdY0Khc9TGB9++VMSG5TrD15YJId...
                   gYALEI7m1jJKpHWAEs0hiemw5VmKyIZpzGstSJsFStERlAjiETDH...
                   YAtnI4J8dRyP9I7BOVOn3wNfIjk85gi1/0Oc+j8S65giLAfndWGR...
                   9R9wIkm5BMUcSRRcDy0yuwKBgEbkOnGGSD0ah4HkvrUkepIbUDTD...
                   AnEBM1cXI5UT7BfKInpUihZi59QhgdK/hkOSmWhlZGWikJ5VizBf...
                   drkBr/vTKVRMTi3lVFB7KkIV1xJxC5E/BZ+YdZEpWoCZAoGAC/Cd...
                   TTld5N6opgOXAcQJwzqoGa9ZMwc5Q9f4bfRc67emkw0ZAAwSsvWR...
                   x3O2duuy7/smTwWwskEWRK5IrUxoMv/VVYaqdzcOajwieNrblr7c...
                   -----END RSA PRIVATE KEY-----
```

The `KeyMaterial` member stores the private key for the key pair. The public key is stored in AWS. You can't retrieve the public key from AWS, but you can verify the public key by comparing the `KeyFingerprint` for the private key to that returned from AWS for the public key.

## Viewing the Fingerprint of Your Key Pair
<a name="get-ec2keypair"></a>

You can use the `Get-EC2KeyPair` cmdlet to view the fingerprint for your key pair.

```
PS > Get-EC2KeyPair -KeyName myPSKeyPair | format-list KeyName, KeyFingerprint

  KeyName        : myPSKeyPair
  KeyFingerprint : 09:06:70:8e:26:b6:e7:ef:8f:fe:4a:1d:bc:9c:6a:63:11:ac:ad:3c
```

## Storing Your Private Key
<a name="store-ec2keypair"></a>

To store the private key to a file, pipe the `KeyFingerMaterial` member to the `Out-File` cmdlet.

```
PS > $myPSKeyPair.KeyMaterial | Out-File -Encoding ascii myPSKeyPair.pem
```

You must specify `-Encoding ascii` when writing the private key to a file. Otherwise, tools such as `openssl` might not be able to read the file correctly. You can verify that the format of the resulting file is correct by using a command such as the following:

```
PS > openssl rsa -check < myPSKeyPair.pem
```

(The `openssl` tool is not included with the AWS Tools for PowerShell or the AWS SDK for .NET.)

## Removing Your Key Pair
<a name="remove-ec2keypair"></a>

You need your key pair to launch and connect to an instance. When you are done using a key pair, you can remove it. To remove the public key from AWS, use the `Remove-EC2KeyPair` cmdlet. When prompted, press `Enter` to remove the key pair.

```
PS > Remove-EC2KeyPair -KeyName myPSKeyPair

Confirm
Performing the operation "Remove-EC2KeyPair (DeleteKeyPair)" on target "myPSKeyPair".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```

The variable, `$myPSKeyPair`, still exists in the current PowerShell session and still contains the key pair information. The `myPSKeyPair.pem` file also exists. However, the private key is no longer valid because the public key for the key pair is no longer stored in AWS.

# Create a Security Group Using Windows PowerShell
<a name="pstools-ec2-sg"></a>

You can use the AWS Tools for PowerShell to create and configure a security group. The response is the ID of the security group.

If you need to connect to your instance, you must configure the security group to allow SSH traffic (Linux) or RDP traffic (Windows).

**Topics**
+ [

## Prerequisites
](#sg-prerequisites)
+ [

## Creating a Security Group for EC2-VPC
](#new-ec2securitygroup-vpc)

## Prerequisites
<a name="sg-prerequisites"></a>

You need the public IP address of your computer, in CIDR notation. You can get the public IP address of your local computer using a service. For example, Amazon provides the following service: [http://checkip.amazonaws.com/](http://checkip.amazonaws.com/) or [https://checkip.amazonaws.com/](https://checkip.amazonaws.com/). To locate another service that provides your IP address, use the search phrase "what is my IP address". If you are connecting through an ISP or from behind your firewall without a static IP address, you need to find the range of IP addresses that can be used by your client computers.

**Warning**  
If you specify `0.0.0.0/0`, you are enabling traffic from any IP addresses in the world. For the SSH and RDP protocols, you might consider this acceptable for a short time in a test environment, but it's unsafe for production environments. In production, be sure to authorize access only from the appropriate individual IP address or range of addresses.

## Creating a Security Group for EC2-VPC
<a name="new-ec2securitygroup-vpc"></a>

**Warning**  
EC2-Classic was retired on August 15, 2022. We recommend that you migrate from EC2-Classic to a VPC. For more information, see the blog post [EC2-Classic Networking is Retiring – Here's How to Prepare](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

The following `New-EC2SecurityGroup` example adds the `-VpcId` parameter to create a security group for the specified VPC.

```
PS > $groupid = New-EC2SecurityGroup `
    -VpcId "vpc-da0013b3" `
    -GroupName "myPSSecurityGroup" `
    -GroupDescription "EC2-VPC from PowerShell"
```

To view the initial configuration of the security group, use the `Get-EC2SecurityGroup` cmdlet. By default, the security group for a VPC contains a rule that allows all outbound traffic. Notice that you can't reference a security group for EC2-VPC by name.

```
PS > Get-EC2SecurityGroup -GroupId sg-5d293231

OwnerId             : 123456789012
GroupName           : myPSSecurityGroup
GroupId             : sg-5d293231
Description         : EC2-VPC from PowerShell
IpPermissions       : {}
IpPermissionsEgress : {Amazon.EC2.Model.IpPermission}
VpcId               : vpc-da0013b3
Tags                : {}
```

To define the permissions for inbound traffic on TCP port 22 (SSH) and TCP port 3389, use the `New-Object` cmdlet. The following example script defines permissions for TCP ports 22 and 3389 from a single IP address, `203.0.113.25/32`.

```
$ip1 = new-object Amazon.EC2.Model.IpPermission 
$ip1.IpProtocol = "tcp" 
$ip1.FromPort = 22 
$ip1.ToPort = 22 
$ip1.IpRanges.Add("203.0.113.25/32") 
$ip2 = new-object Amazon.EC2.Model.IpPermission 
$ip2.IpProtocol = "tcp" 
$ip2.FromPort = 3389 
$ip2.ToPort = 3389 
$ip2.IpRanges.Add("203.0.113.25/32") 
Grant-EC2SecurityGroupIngress -GroupId $groupid -IpPermissions @( $ip1, $ip2 )
```

To verify the security group has been updated, use the `Get-EC2SecurityGroup` cmdlet again.

```
PS > Get-EC2SecurityGroup -GroupIds sg-5d293231

OwnerId             : 123456789012
GroupName           : myPSSecurityGroup
GroupId             : sg-5d293231
Description         : EC2-VPC from PowerShell
IpPermissions       : {Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {Amazon.EC2.Model.IpPermission}
VpcId               : vpc-da0013b3
Tags                : {}
```

To view the inbound rules, you can retrieve the `IpPermissions` property from the collection object returned by the previous command.

```
PS > (Get-EC2SecurityGroup -GroupIds sg-5d293231).IpPermissions

IpProtocol       : tcp
FromPort         : 22
ToPort           : 22
UserIdGroupPairs : {}
IpRanges         : {203.0.113.25/32}

IpProtocol       : tcp
FromPort         : 3389
ToPort           : 3389
UserIdGroupPairs : {}
IpRanges         : {203.0.113.25/32}
```

# Find an Amazon Machine Image Using Windows PowerShell
<a name="pstools-ec2-get-amis"></a>

When you launch an Amazon EC2 instance, you specify an Amazon Machine Image (AMI) to serve as a template for the instance. However, the IDs for the AWS Windows AMIs change frequently because AWS provides new AMIs with the latest updates and security enhancements. You can use the [Get-EC2Image](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-EC2Image.html) cmdlet to find the current Windows AMIs and get their IDs.

## Get-EC2Image
<a name="pstools-ec2-get-image"></a>

The `Get-EC2Image` cmdlet retrieves a list of AMIs that you can use.

Use the `-Owner` parameter with the array value `amazon, self` so that `Get-EC2Image` retrieves only AMIs that belong to Amazon or to you. In this context, *you* refers to the user whose credentials you used to invoke the cmdlet.

```
PS > Get-EC2Image -Owner amazon, self
```

You can scope the results using the `-Filter` parameter. To specify the filter, create an object of type `Amazon.EC2.Model.Filter`. For example, use the following filter to display only Windows AMIs.

```
$platform_values = New-Object 'collections.generic.list[string]'
$platform_values.add("windows")
$filter_platform = New-Object Amazon.EC2.Model.Filter -Property @{Name = "platform"; Values = $platform_values}
Get-EC2Image -Owner amazon, self -Filter $filter_platform
```

The following is an example of one of the AMIs returned by the cmdlet; the actual output of the previous command provides information for many AMIs.

```
Architecture        : x86_64
BlockDeviceMappings : {/dev/sda1, xvdca, xvdcb, xvdcc…}
CreationDate        : 2019-06-12T10:41:31.000Z
Description         : Microsoft Windows Server 2019 Full Locale English with SQL Web 2017 AMI provided by Amazon
EnaSupport          : True
Hypervisor          : xen
ImageId             : ami-000226b77608d973b
ImageLocation       : amazon/Windows_Server-2019-English-Full-SQL_2017_Web-2019.06.12
ImageOwnerAlias     : amazon
ImageType           : machine
KernelId            : 
Name                : Windows_Server-2019-English-Full-SQL_2017_Web-2019.06.12
OwnerId             : 801119661308
Platform            : Windows
ProductCodes        : {}
Public              : True
RamdiskId           : 
RootDeviceName      : /dev/sda1
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         : 
Tags                : {}
VirtualizationType  : hvm
```

**Note**  
Version 4 of the AWS Tools for PowerShell provided the `Get-EC2ImageByName` cmdlet to filter the list of AMIs by name patterns. For version 5 of the tools, use the [Get-SSMLatestEC2Image](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-SSMLatestEC2Image.html) cmdlet instead.

# Launch an Amazon EC2 Instance Using Windows PowerShell
<a name="pstools-ec2-launch"></a>

To launch an Amazon EC2 instance, you need the key pair and security group that you created in the previous sections. You also need the ID of an Amazon Machine Image (AMI). For more information, see the following documentation:
+  [Creating a Key Pair](pstools-ec2-keypairs.md) 
+  [Create a Security Group Using Windows PowerShell](pstools-ec2-sg.md) 
+  [Find an Amazon Machine Image Using Windows PowerShell](pstools-ec2-get-amis.md) 

**Important**  
If you launch an instance that is not within the Free Tier, you are billed after you launch the instance and charged for the time that the instance is running even if it remains idle.

**Topics**
+ [

## Launching an Instance in a VPC
](#new-ec2instance-vpc)
+ [

## Launching a Spot Instance in a VPC
](#new-ec2instance-spot)

## Launching an Instance in a VPC
<a name="new-ec2instance-vpc"></a>

**Warning**  
EC2-Classic was retired on August 15, 2022. We recommend that you migrate from EC2-Classic to a VPC. For more information, see the blog post [EC2-Classic Networking is Retiring – Here's How to Prepare](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

The following command creates a single `m1.small` instance in the specified private subnet. The security group must be valid for the specified subnet.

```
PS > New-EC2Instance `
    -ImageId ami-c49c0dac `
    -MinCount 1 -MaxCount 1 `
    -KeyName myPSKeyPair `
    -SecurityGroupId sg-5d293231 `
    -InstanceType m1.small `
    -SubnetId subnet-d60013bf

ReservationId   : r-b70a0ef1
OwnerId         : 123456789012
RequesterId     :
Groups          : {}
GroupName       : {}
Instances       : {}
```

Your instance is in the `pending` state initially, but is in the `running` state after a few minutes. To view information about your instance, use the `Get-EC2Instance` cmdlet. If you have more than one instance, you can filter the results on the reservation ID using the `Filter` parameter. First, create an object of type `Amazon.EC2.Model.Filter`. Next, call `Get-EC2Instance` that uses the filter, and then displays the `Instances` property.

```
PS > $reservation = New-Object 'collections.generic.list[string]'
PS > $reservation.add("r-b70a0ef1")
PS > $filter_reservation = New-Object Amazon.EC2.Model.Filter -Property @{Name = "reservation-id"; Values = $reservation}
PS > (Get-EC2Instance -Filter $filter_reservation).Instances

AmiLaunchIndex        : 0
Architecture          : x86_64
BlockDeviceMappings   : {/dev/sda1}
ClientToken           :
EbsOptimized          : False
Hypervisor            : xen
IamInstanceProfile    :
ImageId               : ami-c49c0dac
InstanceId            : i-5203422c
InstanceLifecycle     :
InstanceType          : m1.small
KernelId              :
KeyName               : myPSKeyPair
LaunchTime            : 12/2/2018 3:38:52 PM
Monitoring            : Amazon.EC2.Model.Monitoring
NetworkInterfaces     : {}
Placement             : Amazon.EC2.Model.Placement
Platform              : Windows
PrivateDnsName        :
PrivateIpAddress      : 10.25.1.11
ProductCodes          : {}
PublicDnsName         :
PublicIpAddress       : 198.51.100.245
RamdiskId             :
RootDeviceName        : /dev/sda1
RootDeviceType        : ebs
SecurityGroups        : {myPSSecurityGroup}
SourceDestCheck       : True
SpotInstanceRequestId :
SriovNetSupport       :
State                 : Amazon.EC2.Model.InstanceState
StateReason           :
StateTransitionReason :
SubnetId              : subnet-d60013bf
Tags                  : {}
VirtualizationType    : hvm
VpcId                 : vpc-a01106c2
```

## Launching a Spot Instance in a VPC
<a name="new-ec2instance-spot"></a>

The following example script requests a Spot Instance in the specified subnet. The security group must be one you created for the VPC that contains the specified subnet.

```
$interface1 = New-Object Amazon.EC2.Model.InstanceNetworkInterfaceSpecification
$interface1.DeviceIndex = 0
$interface1.SubnetId = "subnet-b61f49f0"
$interface1.PrivateIpAddress = "10.0.1.5"
$interface1.Groups.Add("sg-5d293231")
Request-EC2SpotInstance `
    -SpotPrice 0.007 `
    -InstanceCount 1 `
    -Type one-time `
    -LaunchSpecification_ImageId ami-7527031c `
    -LaunchSpecification_InstanceType m1.small `
    -Region us-west-2 `
    -LaunchSpecification_NetworkInterfaces $interface1
```

# AWS Lambda and AWS Tools for PowerShell
<a name="pstools-lambda"></a>

By using the [AWSLambdaPSCore](https://www.powershellgallery.com/packages/AWSLambdaPSCore) module, you can develop AWS Lambda functions in PowerShell Core 6.0 using the .NET Core 2.1 runtime. PowerShell developers can manage AWS resources and write automation scripts in the PowerShell environment by using Lambda. PowerShell support in Lambda lets you run PowerShell scripts or functions in response to any Lambda event, such as an Amazon S3 event or Amazon CloudWatch scheduled event. The AWSLambdaPSCore module is a separate AWS module for PowerShell; it is not part of the AWS Tools for PowerShell, nor does installing the AWSLambdaPSCore module install the AWS Tools for PowerShell.

After you install the AWSLambdaPSCore module, you can use any available PowerShell cmdlets—or develop your own—to author serverless functions. The AWS Lambda Tools for PowerShell module includes project templates for PowerShell-based serverless applications, and tools to publish projects to AWS.

AWSLambdaPSCore module support is available in all regions that support Lambda. For more information about supported regions, see the [AWS region table](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).

## Prerequisites
<a name="prerequisites"></a>

The following steps are required before you can install and use the AWSLambdaPSCore module. For more detail about these steps, see [Setting Up a PowerShell Development Environment](https://docs.aws.amazon.com/lambda/latest/dg/lambda-powershell-setup-dev-environment.html) in the AWS Lambda Developer Guide.
+  **Install the correct release of PowerShell** – Lambda's support for PowerShell is based on the cross-platform PowerShell Core 6.0 release. You can develop PowerShell Lambda functions on Windows, Linux, or Mac. If you don’t have at least this release of PowerShell installed, instructions are available on the [Microsoft PowerShell documentation website](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell).
+  **Install the .NET Core 2.1 SDK** – Because PowerShell Core is based on .NET Core, the Lambda support for PowerShell uses the same .NET Core 2.1 Lambda runtime for both .NET Core and PowerShell Lambda functions. The Lambda PowerShell publishing cmdlets use the .NET Core 2.1 SDK to create the Lambda deployment package. The .NET Core 2.1 SDK is available from the [Microsoft Download Center](https://www.microsoft.com/net/download). Be sure to install the SDK, not the Runtime.

## Install the AWSLambdaPSCore Module
<a name="install-the-awslambdapscore-module"></a>

After completing the prerequisites, you are ready to install the AWSLambdaPSCore module. Run the following command in a PowerShell Core session.

```
PS> Install-Module AWSLambdaPSCore -Scope CurrentUser
```

You are ready to start developing Lambda functions in PowerShell. For more information about how to get started, see [Programming Model for Authoring Lambda Functions in PowerShell](https://docs.aws.amazon.com/lambda/latest/dg/powershell-programming-model.html) in the AWS Lambda Developer Guide.

## See Also
<a name="see-also"></a>
+  [Announcing Lambda Support for PowerShell Core on the AWS Developer Blog](https://aws.amazon.com/blogs/developer/announcing-lambda-support-for-powershell-core/) 
+  [AWSLambdaPSCore module on the PowerShell Gallery website](https://www.powershellgallery.com/packages/AWSLambdaPSCore/1.0.0.2) 
+  [Setting Up a PowerShell Development Environment](https://docs.aws.amazon.com/lambda/latest/dg/lambda-powershell-setup-dev-environment.html) 
+ [AWS Lambda Tools for Powershell on GitHub](https://github.com/aws/aws-lambda-dotnet/tree/master/PowerShell)
+  [AWS Lambda Console](https://console.aws.amazon.com/lambda/home) 

# Amazon SQS, Amazon SNS and Tools for Windows PowerShell
<a name="pstools-sqs-queue-sns-topic"></a>

This section provides examples that show how to:
+ Create an Amazon SQS queue and get queue ARN (Amazon Resource Name).
+ Create an Amazon SNS topic.
+ Give permissions to the SNS topic so that it can send messages to the queue.
+ Subscribe the queue to the SNS topic
+ Give IAM users or AWS accounts permissions to publish to the SNS topic and read messages from the SQS queue.
+ Verify results by publishing a message to the topic and reading the message from the queue.

## Create an Amazon SQS queue and get queue ARN
<a name="pstools-create-sqs-queue"></a>

The following command creates an SQS queue in your default region. The output shows the URL of the new queue.

```
PS > New-SQSQueue -QueueName myQueue
https://sqs.us-west-2.amazonaws.com/123456789012/myQueue
```

The following command retrieves the ARN of the queue.

```
PS > Get-SQSQueueAttribute -QueueUrl https://sqs.us-west-2.amazonaws.com/123456789012/myQueue -AttributeName QueueArn
...
QueueARN               : arn:aws:sqs:us-west-2:123456789012:myQueue
...
```

## Create an Amazon SNS topic
<a name="pstools-create-sns-topic"></a>

The following command creates an SNS topic in your default region, and returns the ARN of the new topic.

```
PS > New-SNSTopic -Name myTopic
arn:aws:sns:us-west-2:123456789012:myTopic
```

## Give permissions to the SNS topic
<a name="pstools-permissions-sns-topic"></a>

The following example script creates both an SQS queue and an SNS topic, and grants permissions to the SNS topic so that it can send messages to the SQS queue:

```
# create the queue and topic to be associated
$qurl = New-SQSQueue -QueueName "myQueue"
$topicarn = New-SNSTopic -Name "myTopic"

# get the queue ARN to inject into the policy; it will be returned
# in the output's QueueARN member but we need to put it into a variable
# so text expansion in the policy string takes effect
$qarn = (Get-SQSQueueAttribute -QueueUrl $qurl -AttributeNames "QueueArn").QueueARN

# construct the policy and inject arns
$policy = @"
{
    "Version": "2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "SQS:SendMessage",
        "Resource": "$qarn",
        "Condition": { "ArnEquals": { "aws:SourceArn": "$topicarn" } }
    }
}
"@

# set the policy
Set-SQSQueueAttribute -QueueUrl $qurl -Attribute @{ Policy=$policy }
```

## Subscribe the queue to the SNS topic
<a name="pstools-subscribe-queue-topic"></a>

The following command subscribes the queue `myQueue` to the SNS topic `myTopic`, and returns the Subscription ID:

```
PS > Connect-SNSNotification `
    -TopicARN arn:aws:sns:us-west-2:123456789012:myTopic `
    -Protocol SQS `
    -Endpoint arn:aws:sqs:us-west-2:123456789012:myQueue
arn:aws:sns:us-west-2:123456789012:myTopic:f8ff77c6-e719-4d70-8e5c-a54d41feb754
```

## Give permissions
<a name="pstools-permissions-publish-read"></a>

The following command grants permission to perform the `sns:Publish` action on the topic `myTopic`

```
PS > Add-SNSPermission `
    -TopicArn arn:aws:sns:us-west-2:123456789012:myTopic `
    -Label ps-cmdlet-topic `
    -AWSAccountIds 123456789012 `
    -ActionNames publish
```

The following command grants permission to perform the `sqs:ReceiveMessage` and `sqs:DeleteMessage` actions on the queue `myQueue`.

```
PS > Add-SQSPermission `
    -QueueUrl https://sqs.us-west-2.amazonaws.com/123456789012/myQueue `
    -AWSAccountId "123456789012" `
    -Label queue-permission `
    -ActionName SendMessage, ReceiveMessage
```

## Verify results
<a name="pstools-verify-publish-read"></a>

The following command tests your new queue and topic by publishing a message to the SNS topic `myTopic` and returns the `MessageId`.

```
PS > Publish-SNSMessage `
    -TopicArn arn:aws:sns:us-west-2:123456789012:myTopic `
    -Message "Have A Nice Day!"
728180b6-f62b-49d5-b4d3-3824bb2e77f4
```

The following command retrieves the message from the SQS queue `myQueue` and displays it.

```
PS > Receive-SQSMessage -QueueUrl https://sqs.us-west-2.amazonaws.com/123456789012/myQueue

Attributes             : {}
Body                   : {
                           "Type" : "Notification",
                           "MessageId" : "491c687d-b78d-5c48-b7a0-3d8d769ee91b",
                           "TopicArn" : "arn:aws:sns:us-west-2:123456789012:myTopic",
                           "Message" : "Have A Nice Day!",
                           "Timestamp" : "2019-09-09T21:06:27.201Z",
                           "SignatureVersion" : "1",
                           "Signature" : "llE17A2+XOuJZnw3TlgcXz4C4KPLXZxbxoEMIirelhl3u/oxkWmz5+9tJKFMns1ZOqQvKxk+ExfEZcD5yWt6biVuBb8pyRmZ1bO3hUENl3ayv2WQiQT1vpLpM7VEQN5m+hLIiPFcs
                         vyuGkJReV7lOJWPHnCN+qTE2lId2RPkFOeGtLGawTsSPTWEvJdDbLlf7E0zZ0q1niXTUtpsZ8Swx01X3QO6u9i9qBFt0ekJFZNJp6Avu05hIklb4yoRs1IkbLVNBK/y0a8Yl9lWp7a7EoWaBn0zhCESe7o
                         kZC6ncBJWphX7KCGVYD0qhVf/5VDgBuv9w8T+higJyvr3WbaSvg==",
                           "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-6aad65c2f9911b05cd53efda11f913f9.pem",
                           "UnsubscribeURL" : 
                         "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:myTopic:22b77de7-a216-4000-9a23-bf465744ca84"
                         }
MD5OfBody              : 5b5ee4f073e9c618eda3718b594fa257
MD5OfMessageAttributes : 
MessageAttributes      : {}
MessageId              : 728180b6-f62b-49d5-b4d3-3824bb2e77f4
ReceiptHandle          : AQEB2vvk1e5cOKFjeIWJticabkc664yuDEjhucnIOqdVUmie7bX7GiJbl7F0enABUgaI2XjEcNPxixhVc/wfsAJZLNHnl8SlbQa0R/kD+Saqa4OIvfj8x3M4Oh1yM1cVKpYmhAzsYrAwAD5g5FvxNBD6zs
                         +HmXdkax2Wd+9AxrHlQZV5ur1MoByKWWbDbsqoYJTJquCclOgWIak/sBx/daBRMTiVQ4GHsrQWMVHtNC14q7Jy/0L2dkmb4dzJfJq0VbFSX1G+u/lrSLpgae+Dfux646y8yFiPFzY4ua4mCF/SVUn63Spy
                         sHN12776axknhg3j9K/Xwj54DixdsegnrKoLx+ctI+0jzAetBR66Q1VhIoJAq7s0a2MseyOeM/Jjucg6Sr9VUnTWVhV8ErXmotoiEg==
```

# CloudWatch from the AWS Tools for Windows PowerShell
<a name="pstools-cw"></a>

This section shows an example of how to use the Tools for Windows PowerShell to publish custom metric data to CloudWatch.

This example assumes that you have set default credentials and a default region for your PowerShell session. 

## Publish a Custom Metric to Your CloudWatch Dashboard
<a name="pstools-cw-custom-metric-publish"></a>

The following PowerShell code initializes an CloudWatch `MetricDatum` object and posts it to the service. You can see the result of this operation by navigating to the [CloudWatch console](https://console.aws.amazon.com/cloudwatch/home).

```
$dat = New-Object Amazon.CloudWatch.Model.MetricDatum
$dat.Timestamp = (Get-Date).ToUniversalTime()
$dat.MetricName = "New Posts"
$dat.Unit = "Count"
$dat.Value = ".50"
Write-CWMetricData -Namespace "Usage Metrics" -MetricData $dat
```

Note the following:
+ The date-time information that you use to initialize `$dat.Timestamp` must be in Universal Time (UTC).
+ The value that you use to initialize `$dat.Value` can be either a string value enclosed in quotes, or a numeric value (no quotes). The example shows a string value.

## See Also
<a name="see-also"></a>
+  [Calling AWS services in the AWS Tools for PowerShell](pstools-using.md) 
+  [AmazonCloudWatchClient.PutMetricData](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudWatch/MCloudWatchPutMetricDataPutMetricDataRequest.html) (.NET SDK Reference)
+  [MetricDatum](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html) (Service API Reference)
+  [Amazon CloudWatch Console](https://console.aws.amazon.com/cloudwatch/home) 

# Using the ClientConfig parameter in cmdlets
<a name="pstools-clientconfig"></a>

The `ClientConfig` parameter can be used to specify certain configuration settings when you connect to a service. Most of the possible properties of this parameter are defined in the [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Runtime/TClientConfig.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Runtime/TClientConfig.html) class, which is inherited into the APIs for AWS services. For an example of simple inheritance, see the [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Keyspaces/TKeyspacesConfig.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Keyspaces/TKeyspacesConfig.html) class. In addition, some services define additional properties that are appropriate only for that service. For an example of additional properties that have been defined, see the [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Config.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Config.html) class, specifically the `ForcePathStyle` property.

## Using the `ClientConfig` parameter
<a name="clientconfig-operation"></a>

To use the `ClientConfig` parameter, you can specify it on the command line as a `ClientConfig` object or use PowerShell splatting to pass a collection of parameter values to a command as a unit. These methods are shown in the following examples. The examples assume that the `AWS.Tools.S3` module has been installed and imported, and that you have a `[default]` credentials profile with appropriate permissions.

******Defining a `ClientConfig` object**

```
$s3Config = New-Object -TypeName Amazon.S3.AmazonS3Config
$s3Config.ForcePathStyle = $true
$s3Config.Timeout = [TimeSpan]::FromMilliseconds(150000)
Get-S3Object -BucketName <BUCKET_NAME> -ClientConfig $s3Config
```

**Adding `ClientConfig` properties by using PowerShell splatting**

```
$params=@{
    ClientConfig=@{
        ForcePathStyle=$true
        Timeout=[TimeSpan]::FromMilliseconds(150000)
    }
    BucketName="<BUCKET_NAME>"
}

Get-S3Object @params
```

## Using an undefined property
<a name="clientconfig-undefined"></a>

When using PowerShell splatting, if you specify a `ClientConfig` property that doesn't exist, the AWS Tools for PowerShell doesn't detect the error until runtime, at which time it returns an exception. Modifying the example from above:

```
$params=@{
    ClientConfig=@{
        ForcePathStyle=$true
        UndefinedProperty="Value"
        Timeout=[TimeSpan]::FromMilliseconds(150000)
    }
    BucketName="<BUCKET_NAME>"
}

Get-S3Object @params
```

This example produces an exception similar to the following:

```
Cannot bind parameter 'ClientConfig'. Cannot create object of type "Amazon.S3.AmazonS3Config". The UndefinedProperty property was not found for the Amazon.S3.AmazonS3Config object.
```

## Specifying the AWS Region
<a name="clientconfig-region"></a>

You can use the `ClientConfig` parameter to set the AWS Region for the command. The Region is set through the `RegionEndpoint` property. The AWS Tools for PowerShell calculates the Region to use according to the following precedence:

1. The `-Region` parameter

1. The Region passed in the `ClientConfig` parameter

1. The PowerShell session state

1. The shared AWS `config` file

1. The environment variables

1. The Amazon EC2 instance metadata, if enabled.