

第 5 版 (V5) AWS Tools for PowerShell 已發行！

如需有關中斷變更和遷移應用程式的資訊，請參閱[遷移主題](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)

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 中呼叫 AWS 服務 AWS Tools for PowerShell
<a name="pstools-using"></a>

本節提供使用 AWS Tools for PowerShell 存取 AWS 服務的範例。這些範例有助於示範如何使用 cmdlet 來執行實際 AWS 任務。這些範例會依賴 Tools for PowerShell 所提供的 cmdlet。若要查看有哪些 cmdlet 可用，請參閱 [AWS Tools for PowerShell cmdlet 參考](https://docs.aws.amazon.com/powershell/v5/reference/)。

您可以在 [程式碼範例](powershell_code_examples.md)章節中找到更多 AWS Tools for PowerShell 範例。

## PowerShell 檔案串連編碼
<a name="powershell-file-concatenation-encoding"></a>

編輯現有 AWS Tools for PowerShell 檔案或記錄中的某些 cmdlet AWS。範例為 `Edit-R53ResourceRecordSet`，這會呼叫適用於 Amazon Route 53 的 [ChangeResourceRecordSets](https://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html) API。

當您在 PowerShell 5.1 或較舊版本中編輯或串連檔案時，PowerShell 會以 UTF-16 而非 UTF-8 輸出編碼。這可能增加不必要的字元，並產生無效的結果。十六進位編輯器可能展現不必要的字元。

為了避免將檔案輸出轉換為 UTF-16，您可以將命令輸送到 PowerShell 的 `Out-File` cmdlet 並指定 UTF-8 編碼，如以下範例所示。

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

如果您是從 PowerShell 主控台執行 AWS CLI 命令，則適用相同的行為。您可以在 `Out-File` PowerShell 主控台中將 AWS CLI 命令的輸出輸送至 。其他 cmdlet，例如 `Export-Csv` 或 `Export-Clixml`，也有一個 `Encoding` 參數。如需具有 `Encoding` 參數以及可讓您更正串連檔案輸出編碼的 cmdlet 完整清單，請執行下列命令：

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

**注意**  
PowerShell 6.0 和更新版本 (包括 PowerShell Core) 會自動保留 UTF-8 編碼以供串連檔案輸出。

## Powershell 工具傳回的物件
<a name="returned-objects-for-the-powershell-tools"></a>

為了在原生 PowerShell 環境中 AWS Tools for PowerShell 更實用， AWS Tools for PowerShell Cmdlet 傳回的物件是 .NET 物件，而不是通常從 AWS SDK 中對應 API 傳回的 JSON 文字物件。例如，`Get-S3Bucket` 會發出 `Buckets` 集合，而非 Amazon S3 JSON 回應物件。`Buckets` 集合可以放置在 PowerShell 管道中，並以適當的方式與之互動。同樣地，`Get-EC2Instance` 會發出 `Reservation` .NET 物件 集合，而非 `DescribeEC2Instances` JSON 結果物件。此行為是設計而成，可讓 AWS Tools for PowerShell 體驗與慣用的 PowerShell 更一致。

如有需要，您可取得實際的服務回應。它們會儲存為傳回物件上的 `note` 屬性。而透過使用 `NextToken` 欄位支援分頁的 API 動作，也會連接為 `note` 屬性。

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

本節會逐步講解啟動 Amazon EC2 執行個體所需的步驟，其包括以下作業：
+ 擷取 Amazon Machine Image (AMI) 的清單。
+ 建立 SSH 驗證的金鑰對。
+ 建立並設定 Amazon EC2 安全群組。
+ 啟動執行個體，並擷取該執行個體的相關資訊。

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

本節會逐步講解建立靜態網站並託管於 Amazon S3 所需的步驟，其將示範以下作業：
+ 建立與刪除 Amazon S3 儲存貯體。
+ 將檔案以物件形式上傳至 Amazon S3 儲存貯體。
+ 刪除 Amazon S3 儲存貯體中的物件。
+ 將 Amazon S3 儲存貯體指定為網站。

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

本節提供 AWS Lambda Tools for PowerShell 模組的簡短概觀，並說明設定模組所需的步驟。

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

本節會逐步講解將 Amazon SQS 佇列訂閱至 Amazon SNS 主題所需的步驟。其將示範以下作業：
+ 建立 Amazon SNS 主題。
+ 建立 Amazon SQS 佇列。
+ 將佇列訂閱至 主題。
+ 傳送訊息至主題。
+ 從佇列接收訊息。

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

您可以善用本節提供的範例，藉此了解如何將自訂資料發布至 CloudWatch。
+ 發布自訂指標至 CloudWatch 儀表板。

## 另請參閱
<a name="see-also"></a>
+  [設定和使用 AWS Tools for PowerShell](pstools-getting-started.md) 

## 主題
<a name="w2aac13c23"></a>
+ [Amazon S3 和 Tools for Windows PowerShell](pstools-s3.md)
+ [Amazon EC2 與 Tools for Windows PowerShell](pstools-ec2.md)
+ [AWS Lambda 而且 AWS Tools for PowerShell](pstools-lambda.md)
+ [Amazon SQS、Amazon SNS 和 Tools for Windows PowerShell](pstools-sqs-queue-sns-topic.md)
+ [來自 的 CloudWatch AWS Tools for Windows PowerShell](pstools-cw.md)
+ [在 cmdlets 中使用用 ClientConfig 參數](pstools-clientconfig.md)

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

在本節中，我們使用 Amazon S3 和 CloudFront AWS Tools for Windows PowerShell 建立靜態網站。在過程中，我們展示這些服務的數個常見任務。本演練是根據[託管靜態網站](https://aws.amazon.com/getting-started/projects/host-static-website/)入門指南所建立，該指南描述使用 [AWS 管理主控台](https://console.aws.amazon.com/s3/home)的類似程序。

此處列出的命令假設您已經設定 PowerShell 工作階段的預設憑證與預設區域；所以，cmdlet 並不會呼叫憑證和區域。

**注意**  
目前沒有適用於重新命名儲存貯體或物件的 Amazon S3 API，因此，沒有可執行此任務的單一 Tools for Windows PowerShell cmdlet。若要重新命名 S3 中的物件，建議您執行 [Copy-S3Object](https://docs.aws.amazon.com/powershell/v5/reference/items/Copy-S3Object.html) cmdlet 使用新名稱複製物件，然後執行 [Remove-S3Object](https://docs.aws.amazon.com/powershell/v5/reference/items/Remove-S3Object.html) cmdlet 刪除原始物件。

**另請參閱**
+  [在 中呼叫 AWS 服務 AWS Tools for PowerShell](pstools-using.md) 
+  [託管於 Amazon S3 的靜態網站](https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) 
+  [Amazon S3 主控台](https://console.aws.amazon.com/s3/home) 

**Topics**
+ [建立 Amazon S3 儲存貯體、驗證其區域，或者加以移除](pstools-s3-bucket-create.md)
+ [設定 Amazon S3 儲存貯體做為網站並啟用記錄](pstools-s3-create-website.md)
+ [將物件上傳至 Amazon S3 儲存貯體](pstools-s3-upload-object.md)
+ [刪除 Amazon S3 物件與儲存貯體](pstools-s3-delete-website.md)
+ [將內嵌文字內容上傳到 Amazon S3](pstools-s3-upload-in-line-text.md)

# 建立 Amazon S3 儲存貯體、驗證其區域，或者加以移除
<a name="pstools-s3-bucket-create"></a>

使用 `New-S3Bucket` cmdlet 來建立新的 Amazon S3 儲存貯體。以下範例會建立名為 `website-example` 的儲存貯體。儲存貯體的名稱必須在所有區域中為唯一。範例會在`us-west-1`區域中建立儲存貯體。

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

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

您可以使用 `Get-S3BucketLocation` cmdlet 驗證儲存貯體所在的區域。

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

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

當你完成本教學後，您就可以使用下面的程式碼刪除這個儲存貯體。但建議您保留這個儲存貯體，因為我們在後續範例會用到它。

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

請注意，儲存貯體移除程序需要較長時間來完成。如果您嘗試立即重新建立同名的儲存貯體，`New-S3Bucket` cmdlet 會失敗，直到舊的儲存貯體完全消失為止。

## 另請參閱
<a name="pstools-seealso-s3-bucket-create"></a>
+  [在 中呼叫 AWS 服務 AWS Tools for PowerShell](pstools-using.md) 
+  [Put Bucket (Amazon S3 服務參考) ](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html) 
+  [AWS Amazon S3 的 PowerShell 區域](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) 

# 設定 Amazon S3 儲存貯體做為網站並啟用記錄
<a name="pstools-s3-create-website"></a>

使用 `Write-S3BucketWebsite` cmdlet 來設定 Amazon S3 儲存貯體做為靜態網站。以下範例指定預設內容網頁的 `index.html` 名稱以及預設錯誤網頁的 `error.html` 名稱。請注意，這個 cmdlet 不會建立這些頁面。需將它們[上傳為 Amazon S3 物件](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    :
```

## 另請參閱
<a name="pstools-seealso-s3-create-website"></a>
+  [在 中呼叫 AWS 服務 AWS Tools for PowerShell](pstools-using.md) 
+  [Put Bucket 網站 (Amazon S3 API 參考)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html) 
+  [Put Bucket ACL (Amazon S3 API 參考)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html) 

# 將物件上傳至 Amazon S3 儲存貯體
<a name="pstools-s3-upload-object"></a>

使用 `Write-S3Object` cmdlet 可從本機檔案系統，將檔案以物件形式上傳至 Amazon S3 儲存貯體。以下範例會建立和上傳兩個簡單的 HTML 檔案至 Amazon S3 儲存貯體，並驗證上傳物件是否存在。`-File` 的 `Write-S3Object` 參數指定本機檔案系統中的檔案名稱。`-Key` 參數指定 Amazon S3 中對應物件的名稱。

Amazon 會從副檔名推斷物件的內容類型，在此例中是「.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
```

 *固定的 ACL 選項* 

使用 Tools for Windows PowerShell 指定固定的 ACL 之值，與 適用於 .NET 的 AWS SDK所用的值相同。不過，請注意，這些值都不同於 Amazon S3 `Put Object` 動作所用的值。Tools for Windows PowerShell 支援下列固定的 ACL：
+ NoACL
+ private
+ public-read
+ public-read-write
+ aws-exec-read
+ authenticated-read
+ bucket-owner-read
+ bucket-owner-full-control
+ log-delivery-write

如需有關這些固定 ACL 設定的詳細資訊，請參閱[存取控制清單概觀](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl)。

## 分段上傳的相關注意事項
<a name="note-regarding-multipart-upload"></a>

如果您使用 Amazon S3 API 來上傳大小大於 5 GB 的檔案，您需要使用分段上傳。不過，Tools for Windows PowerShell 提供的 `Write-S3Object` cmdlet 可以透明的方式處理大於 5 GB 的檔案上傳。

### 測試網站
<a name="pstools-amazon-s3-test-website"></a>

此時，您可以使用瀏覽器瀏覽至網站來測試網站。Amazon S3 中託管的靜態網站 URL 遵循標準格式。

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

例如：

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

### 另請參閱
<a name="pstools-seealso-amazon-s3-test-website"></a>
+  [在 中呼叫 AWS 服務 AWS Tools for PowerShell](pstools-using.md) 
+  [Put 物件 (Amazon S3 API 參考)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html) 
+  [固定的 ACL (Amazon S3 API 參考)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ACLOverview.html#CannedACL) 

# 刪除 Amazon S3 物件與儲存貯體
<a name="pstools-s3-delete-website"></a>

本節會說明如何將您在先前章節中所建立的網站予以刪除。您僅需刪除 HTML 檔案的物件，接著刪除該網站的 Amazon S3 儲存貯體即可。

首先，執行 `Remove-S3Object` cmdlet，從 Amazon S3 儲存貯體中刪除 HTML 檔案的物件。

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

經由 Amazon S3 處理請求的方式，系統預期顯示的成品即為 `False` 回應。在此情況下，該回應並不表示發生問題。

您現在可以執行 `Remove-S3Bucket` cmdlet，刪除該網站目前空白的 Amazon S3 儲存貯體。

```
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    :
```

在 1.1 和更新版本的 中 AWS Tools for PowerShell，您可以將 `-DeleteBucketContent` 參數新增至 `Remove-S3Bucket`，先刪除指定儲存貯體中的所有物件和物件版本，再嘗試移除儲存貯體本身。根據儲存貯體中的物件或物件版本數量，系統可能需要花費大量的時間才能完成此操作。若使用 Tools for Windows PowerShell 1.1 版以前的版本，則儲存貯體必須為空，`Remove-S3Bucket` 才能夠刪除它。

**注意**  
除非您新增 `-Force` 參數，否則 會在 cmdlet 執行之前 AWS Tools for PowerShell 提示您進行確認。

## 另請參閱
<a name="pstools-seealso-amazon-s3-delete-website"></a>
+  [在 中呼叫 AWS 服務 AWS Tools for PowerShell](pstools-using.md) 
+  [刪除物件 (Amazon S3 API 參考)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html) 
+  [DeleteBucket (Amazon S3 API 參考)](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETE.html) 

# 將內嵌文字內容上傳到 Amazon S3
<a name="pstools-s3-upload-in-line-text"></a>

`Write-S3Object` cmdlet 支援將內嵌文字內容上傳至 Amazon S3 的能力。使用 `-Content` 參數 (別名 `-Text`)，您可以指定應上傳到 Amazon S3 的文字型內容，而不需先將它轉換為檔案。參數接受簡單的一行字串，以及包含多行的 here 字串。

```
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 與 Tools for Windows PowerShell
<a name="pstools-ec2"></a>

您可以使用 執行與 Amazon EC2 相關的常見任務 AWS Tools for PowerShell。

此處列出的範例命令假設您已經設定 PowerShell 工作階段的預設憑證與預設區域；因此，當我們呼叫 cmdlet 時不包含憑證或區域。如需詳細資訊，請參閱[使用 驗證 AWS](creds-idc.md)及[AWS 區域](pstools-installing-specifying-region.md)。

**Topics**
+ [建立金鑰對](pstools-ec2-keypairs.md)
+ [建立安全群組](pstools-ec2-sg.md)
+ [尋找 AMI](pstools-ec2-get-amis.md)
+ [啟動 執行個體](pstools-ec2-launch.md)

# 建立金鑰對
<a name="pstools-ec2-keypairs"></a>

以下 `New-EC2KeyPair` 範例會建立金鑰對，並存放在 PowerShell 變數 `$myPSKeyPair` 中 

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

將金鑰對物件輸送到 `Get-Member` Cmdlet，來查看物件的結構。

```
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;}
```

將金鑰對物件輸送到 `Format-List` cmdlet 以檢視 `KeyName`、`KeyFingerprint` 和 `KeyMaterial` 成員的值。(輸出已截斷以利閱讀)。

```
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-----
```

`KeyMaterial` 成員用於存放金鑰對的私有金鑰。公有金鑰存放在 中 AWS。您無法從 擷取公有金鑰 AWS，但您可以透過比較私有金鑰`KeyFingerprint`的 與針對公有金鑰從 傳回的 來驗證公 AWS 有金鑰。

## 檢視金鑰對的指紋
<a name="get-ec2keypair"></a>

您可以使用 `Get-EC2KeyPair` cmdlet 來檢視金鑰對的指紋。

```
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
```

## 存放您的私有金鑰
<a name="store-ec2keypair"></a>

若要將私有金鑰存放至檔案，請將 `KeyFingerMaterial` 成員輸送至 `Out-File` cmdlet。

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

將私有金鑰寫入檔案時，您必須指定 `-Encoding ascii`。否則，`openssl` 等工具將可能無法正確地讀取檔案。您可以使用如下所示的命令，驗證所產生檔案的格式是否正確：

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

( AWS Tools for PowerShell 或 不包含 `openssl`工具 適用於 .NET 的 AWS SDK。)

## 移除您的金鑰對
<a name="remove-ec2keypair"></a>

您需要金鑰對，才能啟動和連線到執行個體。當您使用完金鑰對後，您可以將其移除。若要從中移除公有金鑰 AWS，請使用 `Remove-EC2KeyPair` cmdlet。出現提示時，按下 `Enter` 移除金鑰對。

```
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"):
```

變數 `$myPSKeyPair` 仍然存在於目前的 PowerShell 工作階段，也仍包含金鑰對資訊。`myPSKeyPair.pem` 檔案也存在。不過，私有金鑰不再有效，因為金鑰對的公有金鑰不再存放於 AWS中。

# 使用 Windows PowerShell 建立安全群組
<a name="pstools-ec2-sg"></a>

您可以使用 AWS Tools for PowerShell 來建立和設定安全群組。回應為安全群組的 ID。

如果您需要連接到您的執行個體，則必須設定安全群組以允許 SSH 流量 (Linux) 或 RDP 流量 (Windows)。

**Topics**
+ [先決條件](#sg-prerequisites)
+ [建立適用於 EC2-VPC 的安全群組](#new-ec2securitygroup-vpc)

## 先決條件
<a name="sg-prerequisites"></a>

您需要電腦的公有 IP 地址 (使用 CIDR 表示法)。您可以透過一項服務來取得本機電腦的公有 IP 地址。例如，Amazon 提供以下服務：[http://checkip.amazonaws.com/](http://checkip.amazonaws.com/) 或 [https://checkip.amazonaws.com/](https://checkip.amazonaws.com/)。若要尋找其他能夠提供您的 IP 地址之服務，請搜尋字詞「what is my IP address」(我的 IP 地址為何)。如果您透過 ISP 或是從防火牆後方進行連線，不具備靜態 IP 地址，則需要找到您的用戶端電腦可以使用的 IP 地址範圍。

**警告**  
若您指定 `0.0.0.0/0`，您便會啟用來自世界任何 IP 地址的流量。針對 SSH 和 RDP 通訊協定，您可能會將在測試環境中短暫進行此作業視為沒有問題，但用在生產環境則不安全。在生產環境中，請務必僅授權來自適當個別 IP 地址或地址範圍的存取。

## 建立適用於 EC2-VPC 的安全群組
<a name="new-ec2securitygroup-vpc"></a>

**警告**  
EC2-Classic 在 2022 年 8 月 15 日淘汰。建議您從 EC2-Classic 遷移至 VPC。如需詳細資訊，請參閱部落格文章 [EC2-Classic Networking 正在淘汰 – 以下是如何準備](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/)。

以下 `New-EC2SecurityGroup` 範例會新增 `-VpcId` 參數來建立指定 VPC 的安全群組。

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

若要檢視安全群組的初始設定，請使用 `Get-EC2SecurityGroup` cmdlet。在預設情況下，適用於 VPC 的安全群組包含允許所有對外流量的規則。請注意，EC2-VPC 的安全群組不能按名稱引用。

```
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                : {}
```

若要定義 TCP 連接埠 22 (SSH) 及 TCP 連接埠 3389 上傳入流量的許可，請使用 `New-Object` Cmdlet。以下範例指令碼會定義單一 IP 地址 `203.0.113.25/32` 在 TCP 連接埠 22 和 3389 的許可。

```
$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 )
```

若要驗證安全群組是否已更新，請再次使用 `Get-EC2SecurityGroup` cmdlet。

```
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                : {}
```

若要檢視傳入規則，您可以從先前命令傳回的集合物件中擷取 `IpPermissions` 屬性。

```
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}
```

# 使用 Windows PowerShell 來尋找 Amazon Machine Image
<a name="pstools-ec2-get-amis"></a>

啟動 Amazon EC2 執行個體時，您會指定 Amazon Machine Image (AMI) 做為執行個體的範本。不過， AWS Windows AMIs IDs 會經常變更，因為 AWS 會提供具有最新更新和安全性增強功能的新 AMIs。您可以使用 [Get-EC2Image](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-EC2Image.html) cmdlet 尋找目前的 Windows AMIs 並取得其 IDs。

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

`Get-EC2Image` cmdlet 會擷取您可使用的 AMI 清單。

搭配陣列值 `-Owner` 使用 `amazon, self` 參數，讓 `Get-EC2Image` 僅擷取屬於 Amazon 或您的 AMI。在此內容中，「您」**指的是您使用其憑證來呼叫 Cmdlet 的使用者。

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

您可使用 `-Filter` 參數來限定結果範圍。欲指定篩選條件，請建立類型 `Amazon.EC2.Model.Filter` 的物件。例如，下列篩選條件只會顯示 Windows AMI。

```
$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
```

下列範例為 cmdlet 回傳的 AMI 之一；上述命令的輸出實際提供許多 AMI 的資訊。

```
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
```

**注意**  
第 4 版 AWS Tools for PowerShell 提供 `Get-EC2ImageByName` cmdlet，以依名稱模式篩選 AMIs清單。對於工具的第 5 版，請改用 [Get-SSMLatestEC2Image](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-SSMLatestEC2Image.html) cmdlet。

# 使用 Windows PowerShell 啟動 Amazon EC2 執行個體
<a name="pstools-ec2-launch"></a>

若要啟動 Amazon EC2 執行個體，您需要您在先前章節中建立的金鑰對和安全群組。您也需要 Amazon Machine Image (AMI) 的 ID。如需詳細資訊，請參閱下列 文件：
+  [建立金鑰對](pstools-ec2-keypairs.md) 
+  [使用 Windows PowerShell 建立安全群組](pstools-ec2-sg.md) 
+  [使用 Windows PowerShell 來尋找 Amazon Machine Image](pstools-ec2-get-amis.md) 

**重要**  
如果您啟動的執行個體不包含在免費方案內，則需要在啟動該執行個體後開始收費，收費根據執行個體的執行時間而定，即使其保持閒置狀態仍會計費。

**Topics**
+ [在 VPC 中啟動執行個體](#new-ec2instance-vpc)
+ [在 VPC 中啟動 Spot 執行個體](#new-ec2instance-spot)

## 在 VPC 中啟動執行個體
<a name="new-ec2instance-vpc"></a>

**警告**  
EC2-Classic 在 2022 年 8 月 15 日淘汰。建議您從 EC2-Classic 遷移至 VPC。如需詳細資訊，請參閱部落格文章 [EC2-Classic Networking 正在淘汰 – 以下是如何準備](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/)。

下列命令會在指定的私有子網路中建立單一 `m1.small` 執行個體。安全群組必須針對指定的子網路有效。

```
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       : {}
```

您的執行個體一開始會處於 `pending` 狀態，但在幾分鐘之後就會進入 `running` 狀態。若要檢視執行個體的相關資訊，請使用 `Get-EC2Instance` cmdlet。如果您有多個執行個體，則可以使用 `Filter` 參數來篩選預留 ID 的結果。首先，建立 `Amazon.EC2.Model.Filter` 類型的物件。接下來，請呼叫使用篩選條件的 `Get-EC2Instance`，然後顯示 `Instances` 屬性。

```
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
```

## 在 VPC 中啟動 Spot 執行個體
<a name="new-ec2instance-spot"></a>

以下範例指令碼會請求指定子網路中的 Spot 執行個體。安全群組必須是您為 VPC 所建立，且包含指定的子網路。

```
$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 而且 AWS Tools for PowerShell
<a name="pstools-lambda"></a>

透過使用 [AWSLambdaPSCore](https://www.powershellgallery.com/packages/AWSLambdaPSCore) 模組，您可以使用 .NET Core 2.1 執行時間在 PowerShell Core 6.0 中開發 AWS Lambda 函數。PowerShell 開發人員可以使用 Lambda 在 PowerShell 環境中管理 AWS 資源和撰寫自動化指令碼。Lambda 中的 PowerShell 支援可讓您執行 PowerShell 指令碼或函數，來回應任何 Lambda 事件，例如 Amazon S3 事件或 Amazon CloudWatch 排定事件。AWSLambdaPSCore 模組是 PowerShell 的個別 AWS 模組；它不是 的一部分 AWS Tools for PowerShell，也不會安裝 AWSLambdaPSCore 模組來安裝 AWS Tools for PowerShell。

安裝 AWSLambdaPSCore 模組後，您可以使用任何可用的 PowerShell 或您自行開發的 cmdlet 來編寫無伺服器函數。 AWS Lambda Tools for PowerShell 模組包含 PowerShell 型無伺服器應用程式的專案範本，以及發佈專案的工具 AWS。

所有支援 Lambda 的區域皆支援 AWSLambdaPSCore 模組。如需支援區域的詳細資訊，請參閱 [AWS 區域表](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。

## 先決條件
<a name="prerequisites"></a>

您必須先執行以下必要步驟，才能安裝和使用 AWSLambdaPSCore 模組。如需這些步驟的詳細資訊，請參閱《 AWS Lambda 開發人員指南》中的[設定 PowerShell 開發環境](https://docs.aws.amazon.com/lambda/latest/dg/lambda-powershell-setup-dev-environment.html)。
+  **安裝正確版本的 PowerShell** – Lambda 對 PowerShell 的支援取決於跨平台 PowerShell Core 6.0 版本。您可以在 Windows、Linux、或 Mac 上開發 PowerShell Lambda 函數。如果您尚未安裝此版本 PowerShell，可在 [Microsoft PowerShell 文件網站](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell)中找到指示。
+  **安裝 .NET Core 2.1 開發套件** - 由於 PowerShell Core 是以 .NET Core 為基礎建置而成，在 .NET Core 和 PowerShell Lambda 函數兩方面，PowerShell 的 Lambda 支援皆使用相同的 .NET Core 2.1 Lambda 執行時間。Lambda PowerShell 發佈 cmdlet 使用 .NET Core 2.1 開發套件來建立 Lambda 部署套件。可從 [Microsoft 下載中心](https://www.microsoft.com/net/download)取得 .NET Core 2.1 SDK。請務必安裝軟體開發套件，而非執行時間。

## 安裝 AWSLambdaPSCore 模組
<a name="install-the-awslambdapscore-module"></a>

完成先決條件之後，您就可以安裝 AWSLambdaPSCore 模組。在 PowerShell Core 工作階段中執行下列命令。

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

您已可以開始在 PowerShell 中開始開發 Lambda 函數。如需入門詳細資訊，請參閱《 AWS Lambda 開發人員指南》中的[以 PowerShell 撰寫 Lambda 函數的程式設計模型](https://docs.aws.amazon.com/lambda/latest/dg/powershell-programming-model.html)。

## 另請參閱
<a name="see-also"></a>
+  [在 AWS 開發人員部落格上宣布對 PowerShell Core 的 Lambda 支援](https://aws.amazon.com/blogs/developer/announcing-lambda-support-for-powershell-core/) 
+  [PowerShell Gallery 網站上的 AWSLambdaPSCore 模組](https://www.powershellgallery.com/packages/AWSLambdaPSCore/1.0.0.2) 
+  [設定 PowerShell 開發環境](https://docs.aws.amazon.com/lambda/latest/dg/lambda-powershell-setup-dev-environment.html) 
+ [AWS GitHub 上的適用於 Powershell 的 Lambda 工具](https://github.com/aws/aws-lambda-dotnet/tree/master/PowerShell)
+  [AWS Lambda 主控台](https://console.aws.amazon.com/lambda/home) 

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

本節提供的範例，說明執行以下作業的方法：
+ 建立 Amazon SQS 佇列和取得佇列 ARN (Amazon 資源名稱)。
+ 建立 Amazon SNS 主題。
+ 提供許可給 SNS 主題，以便其可以傳送訊息至佇列。
+ 訂閱佇列至 SNS 主題
+ 授予 IAM 使用者或 AWS 帳戶發佈至 SNS 主題並從 SQS 佇列讀取訊息的許可。
+ 將訊息發佈至主題並讀取來自佇列的訊息以驗證結果。

## 建立 Amazon SQS 佇列和取得佇列 ARN
<a name="pstools-create-sqs-queue"></a>

下列命令會在您的預設區域中建立 SQS 佇列。輸出會顯示新佇列的 URL。

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

下面的命令會擷取佇列的 ARN。

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

## 建立 Amazon SNS 主題
<a name="pstools-create-sns-topic"></a>

下列命令會在您的預設區域中建立 SNS 主題，並傳回新主題的 ARN。

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

## 提供許可給 SNS 主題
<a name="pstools-permissions-sns-topic"></a>

下列範例指令碼會同時建立 SQS 佇列和 SNS 主題，並授與 SNS 主題的許可，以便將訊息傳送到 SQS 佇列：

```
# 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 }
```

## 訂閱佇列至 SNS 主題
<a name="pstools-subscribe-queue-topic"></a>

下列命令會訂閱 SNS 主題 `myTopic` 的佇列 `myQueue`，並傳回訂閱 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
```

## 提供許可
<a name="pstools-permissions-publish-read"></a>

以下命令授予對主題 `myTopic` 執行 `sns:Publish` 動作的許可

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

以下命令授予對佇列 `myQueue` 執行 `sqs:ReceiveMessage` 和 `sqs:DeleteMessage` 動作的許可

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

## 驗證結果
<a name="pstools-verify-publish-read"></a>

下列命令會將訊息發佈至 SNS 主題 `myTopic`，測試您的新佇列和主題，並傳回 `MessageId`。

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

以下命令會從 SQS 佇列 `myQueue` 擷取並顯示訊息。

```
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 AWS Tools for Windows PowerShell
<a name="pstools-cw"></a>

您可以善用本節提供的 Tools for Windows PowerShell 使用範例，藉此透過該工具將自訂指標資料發佈至 CloudWatch。

此範例會假設您已經設定 PowerShell 工作階段的預設憑證與預設區域；

## 發布自訂指標至 CloudWatch 儀表板
<a name="pstools-cw-custom-metric-publish"></a>

以下 PowerShell 程式碼會初始化 CloudWatch `MetricDatum` 物件並將它發佈至服務。瀏覽至 [CloudWatch 主控台](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
```

注意下列事項：
+ 日期與時間資訊必須採用國際標準時間 (UTC)，才能夠用來將 `$dat.Timestamp` 初始化。
+ 加上引號的字串值，或是不加引號的數值皆可用來將 `$dat.Value` 初始化；此範例會顯示字串值。

## 另請參閱
<a name="see-also"></a>
+  [在 中呼叫 AWS 服務 AWS Tools for PowerShell](pstools-using.md) 
+  [AmazonCloudWatchClient.PutMetricData](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudWatch/MCloudWatchPutMetricDataPutMetricDataRequest.html) (.NET 開發套件參考)
+  [MetricDatum](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html) (服務 API 參考)
+  [Amazon CloudWatch 主控台](https://console.aws.amazon.com/cloudwatch/home) 

# 在 cmdlets 中使用用 ClientConfig 參數
<a name="pstools-clientconfig"></a>

當您連線至服務時，此 `ClientConfig` 參數可用來指定特定組態設定。此參數的大部分可能屬性都是在 [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Runtime/TClientConfig.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Runtime/TClientConfig.html)類別中定義，其會繼承至 APIs。 AWS 請參閱 [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Keyspaces/TKeyspacesConfig.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Keyspaces/TKeyspacesConfig.html) 類別以查看簡易的繼承範例。此外，特定服務會定義其他僅適用於該服務的屬性。請參閱 [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Config.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Config.html) 類別以查看其他屬性的範例，尤其是 `ForcePathStyle` 屬性。

## 使用 `ClientConfig` 參數。
<a name="clientconfig-operation"></a>

若要使用 `ClientConfig` 參數，您可以在命令列上將其指定為 `ClientConfig` 物件，或使用 PowerShell splatting 將參數值集合當做一個單位傳遞給命令。這些方法如下範例所示。這些範例預設 `AWS.Tools.S3` 模組已安裝並匯入，而且您的 `[default]` 憑證設定檔具有適當權限。

******定義 `ClientConfig` 物件**

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

**使用 PowerShell splatting 新增 `ClientConfig` 屬性**

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

Get-S3Object @params
```

## 使用未定義的屬性
<a name="clientconfig-undefined"></a>

使用 PowerShell 潑濺時，如果您指定不存在的`ClientConfig`屬性，在執行時間之前， AWS Tools for PowerShell 不會偵測到錯誤，此時會傳回例外狀況。依上述修改範例：

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

Get-S3Object @params
```

此範例會產生類似下列的例外狀況：

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

## 指定 AWS 區域
<a name="clientconfig-region"></a>

您可以使用 `ClientConfig` 參數來設定 命令 AWS 區域 的 。Region (區域) 是透過 `RegionEndpoint` 屬性進行設定。會根據下列優先順序 AWS Tools for PowerShell 計算要使用的區域：

1. `-Region` 參數

1. 在 `ClientConfig` 參數中傳遞的區域

1. PowerShell 工作階段狀態

1. 共用 AWS `config`檔案

1. 環境變數

1. Amazon EC2 執行個體中繼資料 (若已啟用)。