

第 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 Tools for PowerShell
<a name="pstools-getting-started"></a>

本節中的一些主題說明在[安裝工具和設定身分驗證](pstools-getting-set-up.md)之後，使用 Tools for Windows PowerShell 的基本概念。例如，它們說明如何指定 Tools for PowerShell 在與 互動時應使用[AWS 的區域](pstools-installing-specifying-region.md) AWS。

本節中的其他主題提供了一些進階方法的資訊，您可以使用這些方法來設定工具、環境和專案。

**Topics**
+ [AWS 區域](pstools-installing-specifying-region.md)
+ [憑證和設定檔解析](creds-assign.md)
+ [設定聯合身分](saml-pst.md)
+ [可觀測性](observability.md)
+ [Cmdlet 探索和別名](pstools-discovery-aliases.md)
+ [管道、輸出和反覆運算](pstools-pipelines.md)
+ [使用者和角色](pstools-users-roles.md)
+ [使用舊版憑證](pstools-cred-legacy.md)

# 指定 AWS 的區域 AWS Tools for PowerShell
<a name="pstools-installing-specifying-region"></a>

有兩種方式可在執行 AWS Tools for PowerShell 命令時指定要使用 AWS 的區域：
+ 在個別命令上使用 `-Region` 通用參數。
+ 使用 `Set-DefaultAWSRegion` 命令來設定所有命令的預設區域。

如果 Tools for Windows PowerShell 無法找出要使用的區域，許多 AWS cmdlet 會失敗。例外狀況包括 [Amazon S3](pstools-s3.md)、Amazon SES 和 的 cmdlet AWS Identity and Access Management，其會自動預設為全域端點。

 **指定單一 AWS 命令的區域** 

將 `-Region` 參數新增到您的命令，如下。

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

 **若要為目前工作階段中的所有 AWS CLI 命令設定預設區域** 

在 PowerShell 命令提示字元中，輸入下列命令。

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

**注意**  
此設定僅會存在於目前的工作階段。請依照您在 `Import-Module` 命令中的作法，將此命令新增至 PowerShell 設定檔，即可將該設定套用至所有 PowerShell 工作階段。

 **檢視所有 CLI AWS 命令的目前預設區域** 

在 PowerShell 命令提示字元中，輸入下列命令。

```
PS > Get-DefaultAWSRegion

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

 **清除所有 CLI AWS 命令的目前預設區域** 

在 PowerShell 命令提示字元中，輸入下列命令。

```
PS > Clear-DefaultAWSRegion
```

 **檢視所有可用 AWS 區域的清單** 

在 PowerShell 命令提示字元中，輸入下列命令。範例輸出的第三個欄位會識別出目前工作階段的預設區域。

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

**注意**  
系統可能會支援部分區域，但不會在 `Get-AWSRegion` Cmdlet 的輸出中包含該區域。例如，這有時對還不是全域的區域是如此。如果新增 `-Region` 參數至命令仍無法指定區域，請改為嘗試指定自訂端點中的區域，如下節所示。

## 指定自訂或非標準端點
<a name="specifying-a-custom-or-nonstandard-endpoint"></a>

請採用下列範例格式，將 `-EndpointUrl` 常用參數新增至 Tools for Windows PowerShell 命令，即可將自訂端點指定為 URL。

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

以下範例是採用 `Get-EC2Instance` cmdlet。在本範例中，自訂端點位於 `us-west-2`，亦稱美國西部 (奧勒岡)，但您可以使用任何其他支援的 AWS 區域 (包括 `Get-AWSRegion` 未列舉的區域)。

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

## 其他資訊
<a name="region-additional-info"></a>

如需 AWS 區域的詳細資訊，請參閱 *AWS SDKs和工具參考指南*中的[AWS 區域](https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html)。

# 憑證和設定檔解析
<a name="creds-assign"></a>

## 憑證搜尋順序
<a name="cred-provider-chain-main"></a>

當您執行命令時， AWS Tools for PowerShell 會依下列順序搜尋登入資料。當它找到可用的憑證時就會停止。

1. 在命令列中內嵌為參數的文字憑證。

   強烈建議您使用描述檔，不要在命令列中放置文字憑證。

1. `-Credential` 參數指定的憑證。

1. 使用 [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html) Cmdlet 指定的設定檔名稱或設定檔位置。
   + 如果您只指定設定檔名稱，命令會在 AWS SDK 存放區中尋找指定的設定檔，如果不存在，則會從預設位置的 AWS 共用登入資料檔案中尋找指定的設定檔。
   + 如果您只指定描述檔位置，命令會在該憑證檔案中尋找 `default` 描述檔。
   + 如果同時指定名稱和位置，命令就會在該憑證檔案中尋找指定的描述檔。

   如果找不到指定的描述檔或位置，命令會擲出例外狀況。只有在您未指定描述檔或位置時，搜尋才會繼續執行下列步驟。

1. 如果這三個變數都有值，則從 `AWS_ACCESS_KEY_ID`、 `AWS_SECRET_ACCESS_KEY`和 `AWS_SESSION_TOKEN`環境變數建立的登入資料。

1. 名稱為 `AWS_PROFILE`環境變數指定的登入資料設定檔。

1. 依以下順序使用預設描述檔：

   1.  AWS SDK 存放區中的`default`設定檔。

   1. 共用 AWS `credentials`檔案中的`default`設定檔。

   1.  AWS SDK 存放區中的`AWS PS Default`設定檔。

1. 如果命令是在設定使用 IAM 角色的 Amazon EC2 執行個體上執行，就會從執行個體描述檔存取 EC2 執行個體的暫時憑證。

   如需針對 Amazon EC2 執行個體使用 IAM 角色的詳細資訊，請參閱《 [適用於 .NET 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/)》中的[使用角色授予存取權](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-hosm.html)。

如果此搜尋無法找到指定的憑證，命令會擲出例外狀況。

如需環境變數和登入資料設定檔的詳細資訊，請參閱 [AWS SDKs和工具參考指南](https://docs.aws.amazon.com/sdkref/latest/guide/)中的下列主題：[環境變數](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html)、[環境變數清單](https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html#EVarSettings)，以及[共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

# 使用 設定聯合身分 AWS Tools for PowerShell
<a name="saml-pst"></a>

若要讓組織中的使用者存取 AWS 資源，您必須設定標準且可重複的身分驗證方法，以用於安全性、可稽核性、合規性，以及支援角色和帳戶區隔的功能。雖然提供使用者存取 AWS APIs的能力很常見，但沒有聯合 API 存取，您也必須建立 AWS Identity and Access Management (IAM) 使用者，這會破壞使用聯合的目的。本主題說明 中的 SAML （安全性聲明標記語言） 支援 AWS Tools for PowerShell ，可簡化您的聯合存取解決方案。

中的 SAML 支援 AWS Tools for PowerShell 可讓您提供使用者聯合存取 AWS 服務。SAML 是以 XML 為基礎的開放標準格式，可在服務之間傳輸使用者身分驗證和授權資料；特別是身分提供者 （例如 [Active Directory Federation Services](https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/ad-fs-overview)) 與服務提供者 （例如） 之間 AWS。如需有關 SAML 及其運作方式的詳細資訊，請參閱 Wikipedia 上的 [SAML](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language)，或「結構化資訊標準促進組織」(OASIS) 網站上的 [SAML 技術規格](https://www.oasis-open.org/standard/saml/)。中的 SAML 支援與 SAML 2.0 AWS Tools for PowerShell 相容。

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

您必須具備以下項目，才能首次嘗試使用 SAML 支援。
+ 與您的 AWS 帳戶正確整合的聯合身分解決方案，可以僅使用您的組織登入資料進行主控台存取。如需如何專門為 Active Directory 聯合服務執行此操作的詳細資訊，請參閱《*IAM 使用者指南*》中的[關於 SAML 2.0 聯合](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html)，以及部落格文章：[AWS 使用 Windows Active Directory、AD FS 和 SAML 2.0 啟用聯合。](https://aws.amazon.com/blogs/security/enabling-federation-to-aws-using-windows-active-directory-adfs-and-saml-2-0/)雖然部落格文章說明的是 AD FS 2.0，但 AD FS 3.0 的步驟也類似。
+ 安裝在本機工作站 AWS Tools for PowerShell 上的 3.1.31.0 版或更新版本。

## 聯合身分使用者如何取得 AWS 服務 APIs聯合存取權
<a name="saml-pst-federated-process"></a>

下列程序說明 AD FS 如何聯合 Active Directory (AD) 使用者以取得 AWS 資源的存取權。

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


1. 聯合身分使用者電腦上的用戶端會驗證 AD FS。

1. 如果驗證成功，AD FS 會向使用者傳送 SAML 聲明。

1. 使用者的用戶端會將 SAML 聲明傳送至 AWS Security Token Service (STS)，做為 SAML 聯合請求的一部分。

1. STS 會傳回 SAML 回應，其中包含使用者可擔任之角色的 AWS 臨時登入資料。

1. 使用者在 提出的請求中包含這些臨時登入資料，以存取 AWS 服務 APIs AWS Tools for PowerShell。

## SAML 支援如何在 中運作 AWS Tools for PowerShell
<a name="saml-pst-overview"></a>

本節說明 AWS Tools for PowerShell cmdlet 如何為使用者啟用 SAML 型聯合身分的組態。

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


1. AWS Tools for PowerShell 會使用 Windows 使用者目前的登入資料對 AD FS 進行身分驗證，或在使用者嘗試執行需要登入資料才能呼叫的 cmdlet 時，以互動方式進行身分驗證 AWS。

1. AD FS 驗證使用者。

1. AD FS 會產生包含聲明的 SAML 2.0 身分驗證回應；聲明的目的是識別並提供使用者的相關資訊。 會從 SAML 聲明 AWS Tools for PowerShell 中擷取使用者授權角色的清單。

1. AWS Tools for PowerShell 透過發出 `AssumeRoleWithSAMLRequest` API 呼叫，將 SAML 請求，包括請求角色的 Amazon Resource Name (ARN) 轉送至 STS。

1. 如果 SAML 請求是有效的，STS 會傳回回應，其中包含 AWS 、`AccessKeyId`、`SecretAccessKey` 和 `SessionToken`。這些登入資料可持續 3,600 秒 (1 小時)。

1. 使用者現在擁有有效的登入資料，可使用使用者角色有權存取的任何 AWS 服務 APIs。 AWS Tools for PowerShell 會自動將這些登入資料套用至任何後續 AWS API 呼叫，並在過期時自動續約。
**注意**  
當憑證過期且需要新的登入資料時， AWS Tools for PowerShell 會使用 AD FS 自動重新驗證，並取得下個小時的新登入資料。對於已加入網域的使用者帳戶，此程序會以無提示的方式進行。對於未加入網域的帳戶， 會 AWS Tools for PowerShell 提示使用者輸入其登入資料，然後才能重新驗證。

## 如何使用 PowerShell SAML 組態 Cmdlet
<a name="saml-pst-config-cmdlets"></a>

AWS Tools for PowerShell 包含兩個提供 SAML 支援的新 cmdlet。
+  `Set-AWSSamlEndpoint` 會設定您的 AD FS 端點、指派易記的名稱給端點，以及選擇性地說明端點的身分驗證類型。
+  `Set-AWSSamlRoleProfile` 會建立或編輯您想使其與 AD FS 端點建立關聯的使用者帳戶描述檔，透過指定您提供給 `Set-AWSSamlEndpoint` cmdlet 的易記名稱來識別。每個角色描述檔對應到使用者獲權執行的單一角色。

  如同 AWS 登入資料描述檔，您會為角色描述檔指派易記的名稱。您可以搭配 `Set-AWSCredential` cmdlet 使用相同的易記名稱，或做為叫用 AWS 服務 APIs `-ProfileName` 參數值。

開啟新的 AWS Tools for PowerShell 工作階段。如果您執行的是 PowerShell 3.0 或更新版本，則當您執行其任一 cmdlet 時，都會自動匯入 AWS Tools for PowerShell 模組。如果您執行的是 PowerShell 2.0，則必須執行 ``Import-Module`` cmdlet，以手動方式匯入模組，如下列範例所示。

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

### 如何執行 `Set-AWSSamlEndpoint` 和 `Set-AWSSamlRoleProfile` Cmdlet
<a name="how-to-run-the-set-awssamlendpoint-and-set-awssamlroleprofile-cmdlets"></a>

1. 首先，設定 AD FS 系統的端點設定。最簡單的方式是將端點存放在變數中，如本步驟所示。請務必將預留位置帳戶 ID 和 AD FS 主機名稱更換為您自己的帳戶 ID 和 AD FS 主機名稱。在 `Endpoint` 參數中指定 AD FS 主機名稱。

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

1. 若要建立端點設定，請執行 `Set-AWSSamlEndpoint` cmdlet，指定正確的 `AuthenticationType` 參數值。有效值包括 `Basic`、`Digest`、`Kerberos`、`Negotiate` 及 `NTLM`。如果您未指定此參數，預設值是 `Kerberos`。

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

   Cmdlet 會使用 `-StoreAs` 參數傳回您指派的易記名稱，因此您可以在下一行中執行 `Set-AWSSamlRoleProfile` 時使用它。

1. 現在，請執行 `Set-AWSSamlRoleProfile` cmdlet 以向 AD FS 身分提供者驗證身分，並取得讓使用者獲得授權能夠 (在 SAML 聲明中) 執行的一組角色。

   `Set-AWSSamlRoleProfile` cmdlet 使用傳回的一組角色，來提示使用者選取角色以關聯至指定的描述檔，或驗證參數中提供的角色資料是否存在 (如果不存在，系統會提示使用者進行選擇)。如果使用者只獲得一個角色的授權，cmdlet 會自動將該角色關聯至描述檔，而不會提示使用者。不需要提供登入資料即可設定已加入網域的描述檔。

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

   或者，對於non-domain-joined的帳戶，您可以提供 Active Directory 登入資料，然後選取使用者可存取 AWS 的角色，如下行所示。如果您有不同的 Active Directory 使用者帳戶，這可用來區分您組織內的角色 (例如，系統管理函數)。

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

1. 在任何一種情況下，`Set-AWSSamlRoleProfile` cmdlet 都會提示您選擇應在描述檔中存放哪個角色。下列範例顯示兩個可用的角色：`ADFS-Dev` 和 `ADFS-Production`。IAM 角色與 AD FS 系統管理員的 AD 登入資料相關聯。

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

   或者，您可以輸入 `RoleARN`、`PrincipalARN` 和選用的 `NetworkCredential` 參數，在沒有提示的情況下指定角色。如果身分驗證傳回的聲明中未列出指定的角色，系統會提示使用者從可用的角色中選擇。

   ```
   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. 您可以在單一命令中新增 `StoreAllRoles` 參數，為所有角色建立描述檔，如以下程式碼所示。請注意，角色名稱將用於描述檔名稱。

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

### 如何使用角色設定檔來執行需要 AWS 登入資料的 Cmdlet
<a name="how-to-use-role-profiles-to-run-cmdlets-that-require-aws-credentials"></a>

若要執行需要 AWS 登入資料的 cmdlet，您可以使用 AWS 共用登入資料檔案中定義的角色描述檔。將角色描述檔的名稱提供給 `Set-AWSCredential`（或 中任何`ProfileName`參數的值 AWS Tools for PowerShell)，以自動取得描述檔中所述角色的臨時 AWS 登入資料。

雖然您一次只能使用一個角色描述檔，但可以在 shell 工作階段中切換描述檔。當您執行 `Set-AWSCredential` cmdlet 其本身時，此 cmdlet 不會驗證並取得登入資料；cmdlet 會記錄您想要使用指定的角色描述檔。除非您執行需要 AWS 登入資料的 cmdlet，否則無需身分驗證或請求登入資料。

您現在可以使用透過 `SAMLDemoProfile`設定檔取得的臨時 AWS 登入資料來使用 AWS 服務 APIs。以下章節示範如何使用角色描述檔的範例。

### 範例 1：使用 `Set-AWSCredential` 設定預設角色
<a name="example-1-set-a-default-role-with-set-awscredential"></a>

此範例使用 設定 AWS Tools for PowerShell 工作階段的預設角色`Set-AWSCredential`。接著，您可以執行需要登入資料的 cmdlet，並獲得指定角色的授權。此範例列出美國西部 (奧勒岡) 區域的所有 Amazon Elastic Compute Cloud 執行個體，與您透過 `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}
```

### 範例 2：在 PowerShell 工作階段期間變更角色描述檔
<a name="example-2-change-role-profiles-during-a-powershell-session"></a>

此範例列出與`SAMLDemoProfile`設定檔相關聯之角色 AWS 帳戶中所有可用的 Amazon S3 儲存貯體。此範例顯示，雖然您可能已在 AWS Tools for PowerShell 工作階段中稍早使用另一個設定檔，但您可以使用支援該設定檔的 cmdlet 為 `-ProfileName` 參數指定不同的值來變更設定檔。這對於從 PowerShell 命令列管理 Amazon S3 的管理員來說，是常見的任務。

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

請注意，`Get-S3Bucket` cmdlet 指定透過執行 `Set-AWSSamlRoleProfile` cmdlet 而建立之描述檔的名稱。如果您稍早在工作階段中已設定角色描述檔 (例如透過執行 `Set-AWSCredential` cmdlet)，但想為 `Get-S3Bucket` cmdlet 使用不同的角色描述檔，這個命令會很有用。描述檔經理會讓臨時登入資料可用於 `Get-S3Bucket` cmdlet。

雖然登入資料在 1 小時 (STS 強制執行的限制) 後過期，但 AWS Tools for PowerShell 會在工具偵測到目前登入資料過期時請求新的 SAML 聲明，以自動重新整理登入資料。

對於已加入網域的使用者，此程序不會中斷，因為目前使用者的 Windows 身分已用於身分驗證。對於non-domain-joined使用者帳戶， AWS Tools for PowerShell 會顯示請求使用者密碼的 PowerShell 登入資料提示。使用者提供的登入資料，將用於重新驗證使用者並取得新的聲明。

### 範例 3：在區域中取得執行個體
<a name="example-3-get-instances-in-a-region"></a>

以下範例列出亞太區域 (雪梨) 區域的所有 Amazon EC2 執行個體，與 `ADFS-Production` 描述檔使用的帳戶相關聯。這個實用命令很適合用來傳回一個區域中的所有 Amazon EC2 執行個體。

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

## 其他閱讀資料
<a name="saml-pst-reading"></a>

如需如何實作聯合 API 存取的詳細資訊，請參閱[如何使用 SAML 2.0 為聯合 API/CLI 存取實作一般解決方案](https://aws.amazon.com/blogs/security/how-to-implement-a-general-solution-for-federated-apicli-access-using-saml-2-0/)。

如需支援問題或評論，請造訪適用於 [PowerShell 指令碼的](https://forums.aws.amazon.com/forum.jspa?forumID=149) AWS 開發人員論壇或 [.NET Development](https://forums.aws.amazon.com/forum.jspa?forumID=61)。

# 可觀測性
<a name="observability"></a>

可觀測性是從系統發出的資料推斷系統目前狀態的程度。發出的資料通常稱為遙測。如需使用 AWS 服務時遙測的其他資訊，請參閱《 [適用於 .NET 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/)》中的[可觀測性](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/observability.html)。

下列程式碼顯示如何在 中啟用可觀測性的範例 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 探索和別名
<a name="pstools-discovery-aliases"></a>

本節說明如何列出 支援的服務 AWS Tools for PowerShell、如何顯示 提供的一組 Cmdlet AWS Tools for PowerShell 以支援這些服務，以及如何尋找替代 Cmdlet 名稱 （也稱為別名） 以存取這些服務。

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

所有 AWS 服務操作 （或 APIs) 都會記錄在每項服務的 API 參考指南中。舉例來說，請參閱 [IAM API 參考](https://docs.aws.amazon.com/IAM/latest/APIReference/)。在大多數情況下， AWS 服務 API 與 AWS PowerShell Cmdlet one-to-one通訊。若要取得與服務 AWS API 名稱對應的 cmdlet 名稱，請使用 AWS `-ApiOperation` 參數和服務 AWS API 名稱執行 `Get-AWSCmdletName` cmdlet。例如，若要取得以任何可用`DescribeInstances` AWS 服務 API 為基礎的所有可能 cmdlet 名稱，請執行下列命令：

```
PS > Get-AWSCmdletName -ApiOperation DescribeInstances

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

`-ApiOperation` 參數是預設參數，因此您可以省略參數名稱。以下範例相當於先前的範例：

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

如果您知道 API 和服務的名稱，則可以包含 `-Service` 參數以及 cmdlet 名詞字首或服務 AWS 名稱的一部分。例如，適用於 Amazon EC2 的 Cmdlet 名詞字首為 `EC2`。若要取得對應到 Amazon EC2 服務中 `DescribeInstances` API 的 Cmdlet 名稱，請執行以下其中一個命令。他們都會產生相同的輸出：

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

這些命令的參數值有區分大小寫。

如果您不知道所需 AWS 服務 API 或服務的名稱 AWS ，您可以使用 `-ApiOperation` 參數，以及要比對的模式，以及 `-MatchWithRegex` 參數。例如，若要取得包含 `SecurityGroup` 的所有可用 Cmdlet 名稱，執行以下命令：

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

如果您知道 AWS 服務的名稱，但不知道 AWS 服務 API，請同時包含 `-MatchWithRegex` 參數和 `-Service` 參數，將搜尋範圍縮小為單一服務。例如，若只要取得 Amazon EC2 服務中內含 `SecurityGroup` 的所有 Cmdlet 名稱，請執行以下命令

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

如果您知道 AWS Command Line Interface (AWS CLI) 命令的名稱，您可以使用 `-AwsCliCommand` 參數和所需的 AWS CLI 命令名稱來取得以相同 API 為基礎的 cmdlet 名稱。例如，若要取得與 Amazon EC2 服務中`authorize-security-group-ingress` AWS CLI 命令呼叫對應的 cmdlet 名稱，請執行下列命令：

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

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

`Get-AWSCmdletName` cmdlet 只需要足夠的 AWS CLI 命令名稱來識別服務和 AWS API。

若要取得 Tools for PowerShell Core 中所有 Cmdlet 的清單，請執行 PowerShell `Get-Command` Cmdlet，如以下範例所示。

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

您可以搭配 `-Module AWSPowerShell` 執行相同的命令，來查看 AWS Tools for Windows PowerShell中的 Cmdlet。

`Get-Command` Cmdlet 產生的 Cmdlet 清單會以字母順序排序。請注意，根據預設，清單會根據 PowerShell 動詞排序，而非 PowerShell 名詞。

若要改為根據服務來排序結果，請執行以下命令：

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

若要篩選由 `Get-Command` Cmdlet 傳回的 Cmdlet，請將輸出輸送到 PowerShell `Select-String` Cmdlet。例如，若要檢視一組使用 AWS 區域的 cmdlet，請執行下列命令：

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

您亦可篩選 cmdlet 名詞的服務字首，藉此尋找特定服務的 cmdlet。若要查看可用服務字首的清單，請執行 `Get-AWSPowerShellVersion -ListServiceVersionInfo`。以下範例會傳回支援 Amazon CloudWatch Events 服務的 Cmdlet。

```
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 命名和別名
<a name="pstools-cmdlet-naming-aliases"></a>

 AWS Tools for PowerShell 中每個服務的 cmdlet 是根據 服務 AWS SDK 提供的方法。但是，由於 PowerShell 的強制命名慣例，Cmdlet 的名稱可能會和 API 呼叫名稱，或其根據的方法名稱不同。例如，`Get-EC2Instance` cmdlet 是根據 Amazon EC2 `DescribeInstances` 方法。

在某些情況下，cmdlet 名稱可能與方法名稱類似，但實際執行的功能則不同。例如，Amazon S3 `GetObject` 方法會擷取 Amazon S3 物件。然而，`Get-S3Object` cmdlet 會回傳 Amazon S3 物件的*資訊*，而非物件本身。

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

若要使用 取得 S3 物件 AWS Tools for PowerShell，請執行 `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
```

**注意**  
Cmdlet 的 AWS Cmdlet 說明提供 Cmdlet 所依據的 AWS SDK API 名稱。  
如需標準 PowerShell 動詞及其含意的詳細資訊，請參閱[核准的 PowerShell 命令動詞](https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands)。

當您新增 `-Terminate` 參數時，使用動詞的所有 AWS cmdlet – `Remove` 和 `Stop-EC2Instance` cmdlet – 在繼續之前提示確認。若要略過確認，可在命令裡加入 `-Force` 參數。

**重要**  
AWS cmdlet 不支援`-WhatIf`切換。

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

的安裝會 AWS Tools for PowerShell 安裝別名檔案，其中包含許多 AWS cmdlet 的別名。這些別名可能較 cmdlet 名稱更為直觀。例如，服務名稱和 AWS SDK 方法名稱會取代某些別名中的 PowerShell 動詞和名詞。`EC2-DescribeInstances` 別名就是一個範例。

其他別名即使未遵從標準 PowerShell 慣例，但其使用的動詞可能更詳細描述實際操作。例如，別名檔案會將別名 `Get-S3Content` 對應至 cmdlet `Read-S3Object`。

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

別名檔案位於 AWS Tools for PowerShell 安裝目錄中。若要將別名載入到您的環境，請對該檔案使用 *dot-source*命令。以下是 Windows 的範例。

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

針對 Linux 或 macOS shell，它看起來會如下：

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

若要顯示所有 AWS Tools for PowerShell 別名，請執行下列命令。這個命令會使用 PowerShell `Where-Object` Cmdlet 的 `?` 別名，以及 `Source` 屬性來只篩選來自 `AWSPowerShell.NetCore` 模組的別名。

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

...
```

若要在這個檔案中加入您自己的別名，您可能需要將 PowerShell 的 `$MaximumAliasCount` [偏好變數](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-6)值提高為大於 5500 的值。預設值為 4096；最多可以提高到 32768。若要進行這項動作，請執行下列命令。

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

若要確認變更成功，可輸入變數名稱以顯示其目前的值。

```
PS > $MaximumAliasCount
32768
```

# 中的管道、輸出和反覆運算 AWS Tools for PowerShell
<a name="pstools-pipelines"></a>

## 管道
<a name="pstools-pipelining"></a>

PowerShell 鼓勵使用者將 cmdlet 連接到[管道](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines)，將一個 cmdlet 的輸出導向下一個 cmdlet 的輸入。下列範例顯示使用 時的此行為 AWS Tools for PowerShell。命令會取得並停止目前預設區域中的所有 Amazon EC2 執行個體。

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

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

為了更好地支援管道，預設 適用於 .NET 的 AWS SDK 可能會捨棄來自 回應的一些資料。來自 AWS Tools for PowerShell cmdlet 的輸出不會重塑，以將服務回應和結果執行個體作為`Note`屬性包含在發出的集合物件上。而是改為對於發出單一集合做為輸出的這些呼叫，現在將集合列舉到 PowerShell 管道。這表示 SDK 回應和結果資料不能存在於管道中，因為沒有包含可附加的集合物件。

雖然大多數使用者可能不需要此資料，但它對於診斷用途很有用，因為您可以查看 Cmdlet 發出的基礎 AWS 服務呼叫傳送和接收的內容。Cmdlet 可以使用 `-Select *` 參數和引數來傳回整個服務回應。

若要說明如何傳回回應中的所有資料，請考慮下列範例。

第一個範例只會傳回 Amazon S3 儲存貯體的清單。這是預設行為。

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

第二個範例會傳回 適用於 .NET 的 AWS SDK 回應物件。因為 `-Select *` 已指定，所以輸出會包含整個 API 回應，其中包含 `Buckets` 屬性中的儲存貯體集合。在此範例中，`Format-List`Cmdlet 並非絕對必要，但存在以確保顯示所有屬性。

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

## 透過分頁資料反覆運算
<a name="pstools-iteration"></a>

下列各節說明各種可能的反覆運算類型。

### 自動反覆運算
<a name="pstools-iteration-auto"></a>

對於對指定呼叫或支援可分頁結果集施加預設最大傳回物件數量的服務 APIs，大多數 cmdlet 會實作自動反覆運算，以啟用預設行為 "page-to-completion"。在此案例中，Cmdlet 會代表您進行任意數量的呼叫，將完整的資料集傳回管道。

在下列使用 [Get-S3Object](https://docs.aws.amazon.com/powershell/v5/reference/index.html?page=Get-S3Object.html&tocid=Get-S3Object) cmdlet 的範例中， `$result`變數包含名為 之儲存貯體中每個金鑰的`S3Object`執行個體`amzn-s3-demo-bucket1`，這可能是非常大型的資料集。

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

下列範例會將自動反覆運算期間每個頁面的結果數目，從預設值 1000 減少為 500。此範例會執行兩倍的自動重複呼叫，因為每次呼叫只會傳回一半的結果。

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

### 停用自動反覆運算
<a name="pstools-iteration-disable-auto"></a>

如果您希望 Tools for PowerShell 僅傳回資料的第一頁，您可以新增 `-NoAutoIteration` 參數，以防止傳回其他頁面的資料。

下列範例使用 `-NoAutoIteration`和 `-MaxKey` 參數，將傳回的`S3Object`執行個體數量限制為不超過儲存貯體中找到的前 500 個執行個體。

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

若要判斷是否有更多資料可用但未傳回，請使用 `-Select *` 參數和引數，並檢查下一個權杖屬性中是否有值。

`$true` 如果儲存貯體中有 500 個以上的物件，`$false`則以下範例會傳回 。

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

**注意**  
下一個字符回應屬性和 cmdlet 參數的名稱會因 cmdlet 而異。如需詳細資訊，請參閱每個 cmdlet 的說明文件。

### 手動反覆運算
<a name="pstools-iteration-manual"></a>

下列範例使用 [do](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_do) 迴圈傳回儲存貯體中的所有 S3 物件，它會在每次反覆運算後評估條件。`do` 迴圈會執行反覆運算，直到 `Get-S3Object` `$result.NextMarker`設為 為止`$null`，表示不再有分頁資料。迴圈的輸出會指派給 `$s3Objects`變數。

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

此範例使用 PowerShell [潑濺](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting)，以避免因為內嵌宣告參數和引數而造成的長行程式碼。

# 有關使用者和角色的其他資訊
<a name="pstools-users-roles"></a>

若要在 上執行 Tools for PowerShell 命令 AWS，您需要擁有一些適合您任務的使用者、許可集和服務角色組合。

您建立的特定使用者、許可集合和服務角色，以及使用這些角色的方式，將視您的需求而定。以下提供一些額外的資訊，幫助您了解可能使用它們的原因，以及建立的方法。

## 使用者和許可集合
<a name="net-dg-users-roles-user"></a>

雖然可以使用具有長期憑證的 IAM 使用者帳戶來存取 AWS 服務，但這不再是最佳實務，應該避免使用。即使在開發期間，最佳實務是在 中建立使用者和許可集 AWS IAM Identity Center ，並使用身分來源提供的臨時憑證。

若是開發環境，您可以使用您在 [使用 驗證 AWS](creds-idc.md) 中建立或提供給您的使用者。如果您有適當的 AWS 管理主控台 許可，您也可以為該使用者建立具有最低權限的不同許可集，或為開發專案建立專門為開發專案建立新使用者，以提供具有最低權限的許可集。您選擇的行動方式 (如有的話) 取決於您的情況。

如需有關這些使用者和許可集合，以及如何建立它們的詳細資訊，請參閱 *AWS SDK 和工具參考指南*中的[身分驗證和存取](https://docs.aws.amazon.com/sdkref/latest/guide/access.html)和 *AWS IAM Identity Center 使用者指南*中的[入門](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html)。

## 服務角色
<a name="net-dg-users-roles-service-role"></a>

您可以設定 AWS 服務角色來代表使用者存取 AWS 服務。如果有多人將遠端執行您的應用程式，則此類型的存取是適當的；例如，在您為此目的建立的 Amazon EC2 執行個體上。

建立服務角色的程序會根據情況而有所不同，但基本上如下所示。

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。

1. 選擇 **Roles (角色)**，然後選擇 **Create role (建立角色)**。

1. 選擇 **AWS 服務**，尋找並選取 **EC2** (範例)，然後選擇 **EC2** 使用案例 (範例)。

1. 選擇**下一步**，並為您的應用程式將使用 AWS 的服務選取[適當的政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)。
**警告**  
請***勿***選擇 **AdministratorAccess** 政策，因為該政策會啟用您帳戶中幾乎所有內容的讀取和寫入許可。

1. 選擇**下一步**。輸入**角色名稱**、**說明**，以及您想要的任何標籤。

   您可以在 [IAM 使用者指南](https://docs.aws.amazon.com/IAM/latest/UserGuide/)中的[使用 AWS 資源標籤控制存取](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html)中找到標籤的相關資訊。

1. 選擇建**立角色**。

您可以在 [IAM 使用者指南](https://docs.aws.amazon.com/IAM/latest/UserGuide/)中的 [IAM 身分 (使用者、使用者群組和角色)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html#id_iam-roles) 中找到有關 IAM 角色的進階資訊。在 [IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)主題中尋找有關角色的詳細資訊。

# 使用舊版憑證
<a name="pstools-cred-legacy"></a>

本節中的主題提供有關在不使用 AWS IAM Identity Center的情況下使用長期或短期憑證資訊。

**警告**  
為避免安全風險，在開發專用軟體或使用真實資料時，請勿使用 IAM 使用者進行身分驗證。相反地，搭配使用聯合功能和身分提供者，例如 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)。

**注意**  
這些主題中的資訊適用於您需要手動取得及管理短期或長期憑證的情況。有關短期和長期憑證的其他資訊，請參閱 *AWS SDK 和工具參考指南*中的[其他驗證方法](https://docs.aws.amazon.com/sdkref/latest/guide/access-users.html)。  
如需最佳實務，請使用 AWS IAM Identity Center，如 中所述[使用 驗證 AWS](creds-idc.md)。

## 憑證的重要警告和指引
<a name="pstools-creds-warnings-and-guidelines"></a>

**憑證警告**
+ ***請勿使用***您帳戶的根登入資料來存取 AWS 資源。這些登入資料可讓未管制的帳戶存取和很難撤銷這些帳戶。
+ ***請勿***在命令或指令碼中放置常值存取金鑰或憑證資訊。如果這樣做，則會造成意外暴露您的憑證的風險。
+ 請注意，存放在共用 AWS `credentials`檔案中的任何登入資料都會以純文字儲存。

**安全管理憑證的其他指引**

如需如何安全管理 AWS 登入資料的一般討論，請參閱《》中的[AWS 安全登入](https://docs.aws.amazon.com/general/latest/gr/Welcome.html#aws-security-credentials)資料[AWS 一般參考](https://docs.aws.amazon.com/general/latest/gr/)和《[IAM 使用者指南](https://docs.aws.amazon.com/IAM/latest/UserGuide/)》中的[安全最佳實務和使用案例](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPracticesAndUseCases.html)。除了這些討論之外，請考慮下列事項：
+ 建立其他使用者 (例如 IAM Identity Center 中的使用者)，並使用其憑證，而不是使用您的 AWS 根使用者憑證。如有必要，其他使用者的憑證可以被撤銷，或本質上是臨時的。此外，您可以將政策套用至每個使用者，以便僅存取特定資源和動作，從而採取最低權限許可的立場。
+ 使用適用於 Amazon Elastic Container Service (Amazon ECS) 任務的[任務 IAM 角色](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html)。
+ 使用在 Amazon EC2 執行個體上執行的應用程式的 [IAM 角色](shared-credentials-in-aws-powershell.md#shared-credentials-assume-role)。

**Topics**
+ [重要警告和指引](#pstools-creds-warnings-and-guidelines)
+ [AWS 登入資料](specifying-your-aws-credentials.md)
+ [共用憑證](shared-credentials-in-aws-powershell.md)

# 使用 AWS 登入資料
<a name="specifying-your-aws-credentials"></a>

每個 AWS Tools for PowerShell 命令必須包含一組 AWS 登入資料，用於以密碼編譯方式簽署對應的 Web 服務請求。您可以依命令、工作階段或針對所有工作階段指定憑證。

**警告**  
為避免安全風險，在開發專用軟體或使用真實資料時，請勿使用 IAM 使用者進行身分驗證。相反地，搭配使用聯合功能和身分提供者，例如 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)。

**注意**  
本主題中的資訊適用於您需要手動取得及管理短期或長期憑證的情況。有關短期和長期憑證的其他資訊，請參閱 *AWS SDK 和工具參考指南*中的[其他驗證方法](https://docs.aws.amazon.com/sdkref/latest/guide/access-users.html)。  
如需最佳實務，請使用 AWS IAM Identity Center，如 中所述[使用 驗證 AWS](creds-idc.md)。

做為避免公開憑證的最佳實務，請勿在命令中輸入文字憑證。請為您要使用的每一組憑證建立一個描述檔，然後將描述檔存放在兩個憑證存放區的其中一個。在命令中依名稱指定正確的描述檔， AWS Tools for PowerShell 就會擷取相關聯的憑證。如需如何安全管理 AWS 憑證的一般討論，請參閱《》中的[管理 AWS 存取金鑰的最佳實務](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html)*Amazon Web Services 一般參考*。

**注意**  
您需要 AWS 帳戶才能取得登入資料並使用 AWS Tools for PowerShell。若要建立 AWS 帳戶，請參閱[入門：您是第一次 AWS 使用嗎？](https://docs.aws.amazon.com/accounts/latest/reference/welcome-first-time-user.html) *AWS 帳戶管理 參考指南*中的 。

**Topics**
+ [憑證存放區位置](#specifying-your-aws-credentials-store)
+ [管理描述檔](#managing-profiles)
+ [指定憑證](#specifying-your-aws-credentials-use)
+ [憑證搜尋順序](#pstools-cred-provider-chain-legacy)
+ [中的登入資料處理 AWS Tools for PowerShell Core](#credential-handling-in-aws-tools-for-powershell-core)

## 憑證存放區位置
<a name="specifying-your-aws-credentials-store"></a>

 AWS Tools for PowerShell 可以使用兩個登入資料存放區中的任一個：
+ 軟體 AWS 開發套件存放區會加密您的登入資料，並將其存放在您的主資料夾中。在 Windows 中，此存放區位於：`C:\Users\username\AppData\Local\AWSToolkit\RegisteredAccounts.json`。

  [適用於 .NET 的 AWS SDK](https://aws.amazon.com/sdk-for-net/) 和 [Toolkit for Visual Studio](https://aws.amazon.com/visualstudio/) 也可以使用 AWS 開發套件存放區。
+ 共用憑證檔案也位在您的主資料夾中，但以純文字形式存放憑證。

  根據預設，憑證檔案存放在這裡：
  + 在 Windows 上： `C:\Users\username\.aws\credentials`
  + 在 Mac/Linux 上：`~/.aws/credentials`

   AWS SDKs 和 AWS Command Line Interface 也可以使用登入資料檔案。如果您在 AWS 使用者內容之外執行指令碼，請確定包含登入資料的檔案會複製到所有使用者帳戶 （本機系統和使用者） 都可以存取登入資料的位置。

## 管理描述檔
<a name="managing-profiles"></a>

設定檔可讓您使用 參考不同的登入資料集 AWS Tools for PowerShell。您可以使用 AWS Tools for PowerShell cmdlet 來管理 AWS SDK 存放區中的設定檔。您也可以使用 [Toolkit for Visual Studio](https://docs.aws.amazon.com/AWSToolkitVS/latest/UserGuide/tkv_setup.html)，或以程式設計方式使用 [適用於 .NET 的 AWS SDK](https://aws.amazon.com/sdk-for-net/)，來管理 AWS 開發套件存放區中的描述檔。如需如何管理登入資料檔案中設定檔的指示，請參閱[管理 AWS 存取金鑰的最佳實務](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html)。

### 新增新的描述檔
<a name="add-a-new-profile"></a>

若要將新設定檔新增至 AWS SDK 存放區，請執行命令 `Set-AWSCredential`。它會將您的存取金鑰和秘密金鑰存放在您指定之描述檔名稱下的預設憑證檔案中。

```
PS > Set-AWSCredential `
                 -AccessKey AKIA0123456787EXAMPLE `
                 -SecretKey wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY `
                 -StoreAs MyNewProfile
```
+  `-AccessKey`– 存取金鑰 ID。
+  `-SecretKey`– 私密金鑰。
+  `-StoreAs`– 描述檔名稱，必須是唯一的。若要指定預設描述檔，請使用名稱 `default`。

### 更新描述檔
<a name="update-a-profile"></a>

 AWS SDK 存放區必須手動維護。如果您稍後變更服務上的憑證 (例如使用 [IAM 主控台](https://console.aws.amazon.com/iam/home))，使用本機存放的憑證執行命令會失敗，並出現下列錯誤訊息：

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

您可以透過重複描述檔的 `Set-AWSCredential` 命令並將它傳遞到新的存取金鑰和私密金鑰，來更新描述檔。

### 列出描述檔
<a name="list-profiles"></a>

您可以使用以下命令檢查目前的名稱清單。在此範例中，名為 Shirley 的使用者可以存取三個描述檔，這些描述檔都儲存在共用憑證檔案 (`~/.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
```

### 移除描述檔
<a name="remove-a-profile"></a>

若要移除您不再需要的描述檔，請使用以下命令。

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

`-ProfileName` 參數會指定您要刪除的描述檔。

已移除的命令 [Clear-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Clear-AWSCredential.html) 仍適用於回溯相容性，但最好使用 `Remove-AWSCredentialProfile`。

## 指定憑證
<a name="specifying-your-aws-credentials-use"></a>

有幾種方式可以指定憑證。偏好的方法是識別設定檔，而不是將常值登入資料納入命令列。 會使用[登入資料搜尋順序](#pstools-cred-provider-chain-legacy)中所述的搜尋順序來 AWS Tools for PowerShell 尋找設定檔。

在 Windows 上，存放在 AWS SDK 存放區中的 AWS 憑證會使用登入的 Windows 使用者身分加密。它們無法使用其他帳戶解密，也無法在非最初建立帳戶的裝置上使用。若要使用其他使用者的憑證執行任務 (例如，有排程任務要執行的使用者帳戶)，請如上節所述設定憑證描述檔，以便以該使用者身分登入電腦時可以使用其憑證。以任務執行使用者身分登入，完成憑證設定步驟，並建立適用於該使用者的描述檔。登出後，再使用您自己的憑證登入，以設定排程任務。

**注意**  
使用 `-ProfileName` 通用參數來指定描述檔。此參數等同於舊版中的 `-StoredCredentials` 參數 AWS Tools for PowerShell 。如需回溯相容性，`-StoredCredentials` 仍然受支援。

### 預設描述檔 (建議)
<a name="default-profile-recommended"></a>

如果登入資料存放在名為 的設定檔中， AWS SDKs和管理工具可以自動在本機電腦上找到您的登入資料`default`。例如，如果您在本機電腦上有名為 `default` 的描述檔，就不必執行 `Initialize-AWSDefaultConfiguration` cmdlet 或 `Set-AWSCredential` cmdlet。這些工具會自動使用存放在該描述檔中的存取金鑰和秘密金鑰資料。若要使用您預設區域 (`Get-DefaultAWSRegion` 的結果) 以外的 AWS 區域，您可以執行 `Set-DefaultAWSRegion` 並指定區域。

如果您的描述檔並未命名為 `default`，但您想將其做為目前工作階段使用的預設描述檔，則執行 `Set-AWSCredential` 以將其設定為預設描述檔。

雖然執行 `Initialize-AWSDefaultConfiguration` 可讓您針對每個 PowerShell 工作階段指定預設描述檔，cmdlet 仍從您的自訂名稱描述檔載入憑證，並以命名描述檔覆寫 `default` 描述檔。

我們建議您不執行 `Initialize-AWSDefaultConfiguration`，除非您在未經執行個體描述檔啟動的 Amazon EC2 執行個體上執行 PowerShell 工作階段，且您想要手動設定憑證描述檔。請注意，此藍本中的憑證描述檔不包含憑證。在 EC2 執行個體上執行 `Initialize-AWSDefaultConfiguration` 所產生的憑證描述檔，不會直接存放憑證，而是指向執行個體中繼資料 (提供自動輪換的暫時憑證)。但是，它卻會存放執行個體的區域。另一個可能需要執行 `Initialize-AWSDefaultConfiguration` 的情況是，您希望避免執行個體正在運作的區域，對其他區域執行呼叫。執行該命令會永久覆寫存放在執行個體中繼資料的區域。

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

**注意**  
預設登入 AWS 資料包含在 SDK 存放區中的`default`設定檔名稱下。命令會以該名稱覆寫任何現有的描述檔。

如果您的 EC2 執行個體經執行個體描述檔執行，PowerShell 即會自動從執行個體描述檔取得 AWS 憑證和區域資訊。你不需要執行 `Initialize-AWSDefaultConfiguration`。不需要從經執行個體描述檔啟動的 EC2 執行個體上執行 `Initialize-AWSDefaultConfiguration` cmdlet，因為它預設會使用 PowerShell 已經使用的相同執行個體描述檔資料。

### 工作階段描述檔
<a name="session-profile"></a>

使用 `Set-AWSCredential` 指定特定工作階段的預設描述檔。此描述檔會覆寫工作階段期間內的任何預設描述檔。如果您想要在自己的工作階段中使用自訂名稱的描述檔，而不是目前的 `default` 描述檔，建議您使用此方法。

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

**注意**  
在 1.1 版以前的 Tools for Windows PowerShell 版本中，`Set-AWSCredential` cmdlet 無法正常運作，而且會覆寫 "MyProfileName" 指定的描述檔。建議使用較新版本 Tools for Windows PowerShell。

### 命令描述檔
<a name="command-profile"></a>

在個別的命令中，您可以新增 `-ProfileName` 參數以指定僅適用該一個命令的描述檔。此描述檔會覆寫任何預設或工作階段描述檔，如下列範例所示。

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

**注意**  
當您指定預設或工作階段描述檔時，您也可以新增 `-Region` 參數來覆寫預設或工作階段區域。如需詳細資訊，請參閱[指定 AWS 的區域 AWS Tools for PowerShell](pstools-installing-specifying-region.md)。以下範例指定預設的描述檔和區域。  

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

根據預設， AWS 共用的登入資料檔案會假設在使用者的主資料夾中 (`C:\Users\username\.aws`Windows 或 Linux `~/.aws` 上）。若要指定不同位置的憑證檔案，請加上 `-ProfileLocation` 參數並指定憑證檔案路徑。以下範例指定特定命令的非預設憑證檔案。

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

**注意**  
如果您要在通常不會登入 AWS的時間執行 PowerShell 指令碼，例如，在非正常上班時間以排定的任務來執行 PowerShell 指令碼，當您指定要使用的描述檔時請新增 `-ProfileLocation` 參數，並將值設定為存放您憑證之檔案的路徑。為了確保您的 AWS Tools for PowerShell 指令碼使用正確的帳戶登入資料執行，每當指令碼在不使用 AWS 帳戶的內容或程序中執行時，您應該新增 `-ProfileLocation` 參數。您也可以將您的憑證檔案複製到本機系統或指令碼用於執行任務的其他帳戶可存取的位置。

## 憑證搜尋順序
<a name="pstools-cred-provider-chain-legacy"></a>

當您執行命令時， AWS Tools for PowerShell 會依下列順序搜尋登入資料。當它找到可用的憑證時就會停止。

1. 在命令列中內嵌為參數的文字憑證。

   強烈建議您使用描述檔，不要在命令列中放置文字憑證。

1. `-Credential` 參數指定的憑證。

1. 使用 [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html) Cmdlet 指定的設定檔名稱或設定檔位置。
   + 如果您只指定設定檔名稱，命令會在 AWS SDK 存放區中尋找指定的設定檔，如果不存在，則會從預設位置的 AWS 共用登入資料檔案中尋找指定的設定檔。
   + 如果您只指定描述檔位置，命令會在該憑證檔案中尋找 `default` 描述檔。
   + 如果同時指定名稱和位置，命令就會在該憑證檔案中尋找指定的描述檔。

   如果找不到指定的描述檔或位置，命令會擲出例外狀況。只有在您未指定描述檔或位置時，搜尋才會繼續執行下列步驟。

1. 如果這三個變數都有值，則從 `AWS_ACCESS_KEY_ID`、 `AWS_SECRET_ACCESS_KEY`和 `AWS_SESSION_TOKEN`環境變數建立的登入資料。

1. 名稱為 `AWS_PROFILE`環境變數指定的登入資料設定檔。

1. 依以下順序使用預設描述檔：

   1.  AWS SDK 存放區中的`default`設定檔。

   1. 共用 AWS `credentials`檔案中的`default`設定檔。

   1.  AWS SDK 存放區中的`AWS PS Default`設定檔。

1. 如果命令是在設定使用 IAM 角色的 Amazon EC2 執行個體上執行，就會從執行個體描述檔存取 EC2 執行個體的暫時憑證。

   如需針對 Amazon EC2 執行個體使用 IAM 角色的詳細資訊，請參閱《 [適用於 .NET 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/)》中的[使用角色授予存取權](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-hosm.html)。

如果此搜尋無法找到指定的憑證，命令會擲出例外狀況。

如需環境變數和登入資料設定檔的詳細資訊，請參閱 [AWS SDKs和工具參考指南](https://docs.aws.amazon.com/sdkref/latest/guide/)中的下列主題：[環境變數](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html)、[環境變數清單](https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html#EVarSettings)，以及[共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

## 中的登入資料處理 AWS Tools for PowerShell Core
<a name="credential-handling-in-aws-tools-for-powershell-core"></a>

中的 Cmdlet 在執行時 AWS Tools for PowerShell Core 接受 AWS 存取和私密金鑰或登入資料設定檔的名稱，類似於 AWS Tools for Windows PowerShell。在 Windows 上執行時，這兩個模組都能存取 適用於 .NET 的 AWS SDK 憑證存放區檔案 (存放在每個使用者的 `AppData\Local\AWSToolkit\RegisteredAccounts.json` 檔案)。

此檔案以加密格式存放您的金鑰，而且無法用於不同的電腦。這是 AWS Tools for PowerShell 搜尋登入資料設定檔的第一個檔案，也是 AWS Tools for PowerShell 存放登入資料設定檔的檔案。如需 適用於 .NET 的 AWS SDK 登入資料存放區檔案的詳細資訊，請參閱[設定 AWS 登入](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-creds.html)資料。Tools for Windows PowerShell 模組目前不支援將憑證寫入其他檔案或位置。

兩個模組都可以從其他 AWS SDKs 和 所使用的 AWS 共用登入資料檔案讀取設定檔 AWS CLI。在 Windows 上，這個檔案的預設位置是 `C:\Users\<userid>\.aws\credentials`。在非 Windows 平台上，這個檔案存放在 `~/.aws/credentials`。`-ProfileLocation` 參數可用於指向非預設檔案名稱或檔案位置。

開發套件憑證存放區使用 Windows 加密 API，以加密形式存放您的憑證。這些 APIs不適用於其他平台，因此 AWS Tools for PowerShell Core 模組只會使用 AWS 共用的登入資料檔案，並支援將新的登入資料設定檔寫入共用的登入資料檔案。

以下使用 `Set-AWSCredential` cmdlet 的範例指令碼，示範在 Windows 上使用 **AWSPowerShell** 或 **AWSPowerShell.NetCore** 模組來處理憑證描述檔的選項。

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

以下範例說明 Linux 或 macOS 作業系統上的 **AWSPowerShell.NetCore** 模組行為。

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

# 中的共用登入資料 AWS Tools for PowerShell
<a name="shared-credentials-in-aws-powershell"></a>

適用於 Windows PowerShell 的工具支援使用 AWS 共用登入資料檔案，類似於 AWS CLI 和其他 AWS SDKs。適用於 Windows PowerShell 的工具現在支援讀取和寫入 `basic`、 `session`和 `assume role`登入資料設定檔到 .NET 登入資料檔案和 AWS 共用登入資料檔案。此功能透過新的 `Amazon.Runtime.CredentialManagement` 命名空間來啟用。

**警告**  
為避免安全風險，在開發專用軟體或使用真實資料時，請勿使用 IAM 使用者進行身分驗證。相反地，搭配使用聯合功能和身分提供者，例如 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)。

**注意**  
本主題中的資訊適用於您需要手動取得及管理短期或長期憑證的情況。有關短期和長期憑證的其他資訊，請參閱 *AWS SDK 和工具參考指南*中的[其他驗證方法](https://docs.aws.amazon.com/sdkref/latest/guide/access-users.html)。  
如需最佳實務，請使用 AWS IAM Identity Center，如 中所述[使用 驗證 AWS](creds-idc.md)。

已新增至憑證相關 cmdlet、[Initiicize-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) 和 [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html) 的下列參數支援共用 AWS 憑證檔案的新設定檔類型和存取權。在服務 cmdlet 中，您可以新增通用參數 `-ProfileName` 來參考您的描述檔。

## 搭配 使用 IAM 角色 AWS Tools for PowerShell
<a name="shared-credentials-assume-role"></a>

 AWS 共用的登入資料檔案可啟用其他類型的存取。例如，您可以使用 IAM 角色來存取 AWS 資源，而不是 IAM 使用者的長期登入資料。若要執行此作業，您的標準描述檔必須擁有可擔任此角色的許可。當您告知 AWS Tools for PowerShell 使用指定角色的設定檔時， AWS Tools for PowerShell 會查詢 參數識別的設定檔`SourceProfile`。這些憑證可用來請求 `RoleArn` 參數所指定角色的暫時憑證。當第三方擔任角色時，您可以選擇性地要求使用 Multi-Factor Authentication (MFA) 裝置或 `ExternalId` 代碼。


****  

| 參數名稱 | Description | 
| --- | --- | 
|  ExternalId  |  使用者定義的外部 ID，以用於擔任角色 (如果角色要求)。通常只有在您將帳戶的存取權委派給第三方時才需要這麼做。假設指派的角色時，第三方必須包含 ExternalId 做為參數。如需詳細資訊，請參閱《*IAM 使用者指南*》中的[如何在將 AWS 資源的存取權授予第三方時使用外部 ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html)。  | 
|  MfaSerial  |  MFA 序號，以用於擔任角色 (如果角色要求)。如需詳細資訊，請參閱*《IAM 使用者指南》*中的[在 AWS中使用多重要素驗證 (MFA)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)。  | 
|  RoleArn  |  採用角色憑證時擔任的角色 ARN。如需建立和使用角色的詳細資訊，請參閱*《IAM 使用者指南》*中的 [IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)。  | 
|  SourceProfile  |  採用角色憑證所用的來源描述檔名稱。在此描述檔中找到的憑證會用來擔任 `RoleArn` 參數指定的角色。  | 

### 設定擔任角色的描述檔
<a name="setup"></a>

以下範例示範如何設定可直接擔任 IAM 角色的來源描述檔。

第一個命令會建立角色描述檔參考的來源描述檔。第二個命令會建立要擔任哪個角色的角色描述檔。第三個命令會顯示角色描述檔的憑證。

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

若要搭配 Tools for Windows PowerShell 服務 cmdlet 使用此角色描述檔，請將 `-ProfileName` 通用參數新增至命令以參考角色描述檔。下列範例使用上一個範例中定義的角色描述檔來存取 [Get-S3Bucket](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-S3Bucket.html) cmdlet. AWS Tools for PowerShell look 中的登入資料`my_source_profile`、使用這些登入資料來`AssumeRole`代表使用者呼叫 ，然後使用這些臨時角色登入資料來呼叫 `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
```

## 使用憑證描述檔類型
<a name="using-the-credential-profile-types"></a>

若要設定憑證描述檔類型，請先了解哪些參數提供描述檔類型所需的資訊。


****  

| 憑證類型 | 您必須使用的參數 | 
| --- | --- | 
|  **基本** 這些是 IAM 使用者的長期憑證  |  `-AccessKey`  `-SecretKey`  | 
|  **工作階段**： 這些是您手動擷取的 IAM 角色短期憑證，例如直接呼叫 [Use-STSRole](https://docs.aws.amazon.com/powershell/v5/reference/items/Use-STSRole.html) cmdlet。  |  `-AccessKey`  `-SecretKey` `-SessionToken`  | 
|  **角色**： 這些是 AWS Tools for PowerShell 為您擷取的 IAM 角色短期憑證。  |  `-SourceProfile` `-RoleArn`  選用：`-ExternalId` 選用：`-MfaSerial`  | 

## `ProfileLocation` 通用參數
<a name="the-profileslocation-common-parameter"></a>

您可以使用 `-ProfileLocation` 寫入共用憑證檔案，以及指示 cmdlet 讀取憑證檔案。加入 `-ProfileLocation` 參數來控制 Tools for Windows PowerShell 是使用共用憑證檔案或是 .NET 憑證檔案。下表說明參數在 Tools for Windows PowerShell 中的運作方式。


****  

| 描述檔位置值 | 描述檔解析行為 | 
| --- | --- | 
|  null (未設定) 或為空  |  首先，搜尋 .NET 憑證檔案中是否有指定名稱的描述檔。如果找不到設定檔，請在 搜尋 AWS 共用的登入資料檔案`(user's home directory)\.aws\credentials`。  | 
|   AWS 共用登入資料檔案格式的檔案路徑  |  只搜尋指定的檔案中是否有指定名稱的描述檔。  | 

### 將憑證儲存到憑證檔案
<a name="save-credentials-to-a-credentials-file"></a>

若要將憑證寫入並儲存在其中一個憑證檔案，請執行 `Set-AWSCredential` cmdlet。下列範例示範其做法。第一個命令會使用 `Set-AWSCredential` 和 `-ProfileLocation`，將存取金鑰和秘密金鑰新增至 `-ProfileName` 參數指定的描述檔。在第二行，執行 [Get-Content](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content) cmdlet 以顯示憑證檔案的內容。

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

## 顯示您的憑證描述檔
<a name="showing-credential-profiles"></a>

執行 [Get-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Get-AWSCredential.html) cmdlet 並新增 `-ListProfileDetail` 參數以傳回憑證檔案類型和位置，以及描述檔名稱清單。

```
PS > Get-AWSCredential -ListProfileDetail

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

## 移除憑證描述檔
<a name="removing-credential-profiles"></a>

若要移除憑證描述檔，請執行新的 [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) 已移除，但仍適用於回溯相容性。

## 重要說明
<a name="important-notes"></a>

只有 [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) 和 [Set-AWSCredential](https://docs.aws.amazon.com/powershell/v5/reference/items/Set-AWSCredential.html) 支援角色描述檔的參數。您無法直接在 `Get-S3Bucket -SourceProfile source_profile_name -RoleArn arn:aws:iam::999999999999:role/role_name` 等命令中指定角色參數。這不起作用，因為服務 cmdlet 不直接支援 `SourceProfile` 或 `RoleArn` 參數。您反倒必須將這些參數存放在描述檔中，然後使用 `-ProfileName` 參數呼叫命令。