

第 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)

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

# 適用於 PowerShell V5 的 工具程式碼範例
<a name="powershell_code_examples"></a>

本主題中的程式碼範例說明如何搭配 使用 AWS Tools for PowerShell V5 AWS。

*基本概念*是程式碼範例，這些範例說明如何在服務內執行基本操作。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

*案例*是向您展示如何呼叫服務中的多個函數或與其他 AWS 服務組合來完成特定任務的程式碼範例。

有些服務包含其他範例類別，示範如何利用特定於服務的程式庫或函數。

**Topics**
+ [ACM](powershell_acm_code_examples.md)
+ [Application Auto Scaling](powershell_application-auto-scaling_code_examples.md)
+ [WorkSpaces 應用程式](powershell_appstream_code_examples.md)
+ [Aurora](powershell_aurora_code_examples.md)
+ [Auto Scaling](powershell_auto-scaling_code_examples.md)
+ [AWS Budgets](powershell_budgets_code_examples.md)
+ [AWS Cloud9](powershell_cloud9_code_examples.md)
+ [CloudFormation](powershell_cloudformation_code_examples.md)
+ [CloudFront](powershell_cloudfront_code_examples.md)
+ [CloudTrail](powershell_cloudtrail_code_examples.md)
+ [CloudWatch](powershell_cloudwatch_code_examples.md)
+ [CodeCommit：](powershell_codecommit_code_examples.md)
+ [CodeDeploy](powershell_codedeploy_code_examples.md)
+ [CodePipeline](powershell_codepipeline_code_examples.md)
+ [Amazon Cognito 身分](powershell_cognito-identity_code_examples.md)
+ [AWS Config](powershell_config-service_code_examples.md)
+ [Device Farm](powershell_device-farm_code_examples.md)
+ [Directory Service](powershell_directory-service_code_examples.md)
+ [AWS DMS](powershell_database-migration-service_code_examples.md)
+ [DynamoDB](powershell_dynamodb_code_examples.md)
+ [Amazon EC2](powershell_ec2_code_examples.md)
+ [Amazon ECR](powershell_ecr_code_examples.md)
+ [Amazon ECS](powershell_ecs_code_examples.md)
+ [Amazon EFS](powershell_efs_code_examples.md)
+ [Amazon EKS](powershell_eks_code_examples.md)
+ [Elastic Load Balancing - 版本 1](powershell_elastic-load-balancing_code_examples.md)
+ [Elastic Load Balancing - 版本 2](powershell_elastic-load-balancing-v2_code_examples.md)
+ [Amazon FSx](powershell_fsx_code_examples.md)
+ [Amazon Glacier](powershell_glacier_code_examples.md)
+ [AWS Glue](powershell_glue_code_examples.md)
+ [AWS Health](powershell_health_code_examples.md)
+ [IAM](powershell_iam_code_examples.md)
+ [Kinesis](powershell_kinesis_code_examples.md)
+ [Lambda](powershell_lambda_code_examples.md)
+ [Amazon ML](powershell_machine-learning_code_examples.md)
+ [Macie](powershell_macie2_code_examples.md)
+ [AWS 價格表](powershell_pricing_code_examples.md)
+ [資源群組](powershell_resource-groups_code_examples.md)
+ [Resource Groups 標記 API](powershell_resource-groups-tagging-api_code_examples.md)
+ [Route 53](powershell_route-53_code_examples.md)
+ [Amazon S3](powershell_s3_code_examples.md)
+ [Security Hub CSPM](powershell_securityhub_code_examples.md)
+ [Amazon SES](powershell_ses_code_examples.md)
+ [Amazon SES API v2](powershell_sesv2_code_examples.md)
+ [Amazon SNS](powershell_sns_code_examples.md)
+ [Amazon SQS](powershell_sqs_code_examples.md)
+ [AWS STS](powershell_sts_code_examples.md)
+ [支援](powershell_support_code_examples.md)
+ [Systems Manager](powershell_ssm_code_examples.md)
+ [Amazon Translate](powershell_translate_code_examples.md)
+ [AWS WAFV2](powershell_wafv2_code_examples.md)
+ [WorkSpaces](powershell_workspaces_code_examples.md)

# 使用 Tools for PowerShell V5 的 ACM 範例
<a name="powershell_acm_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 ACM 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-ACMCertificate`
<a name="acm_GetCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ACMCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何使用憑證的 ARN 傳回憑證及其鏈結。**  

```
Get-ACMCertificate -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ACMCertificateDetail`
<a name="acm_DescribeCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ACMCertificateDetail`。

**Tools for PowerShell V5**  
**範例 1：傳回指定憑證的詳細資訊。**  

```
Get-ACMCertificateDetail -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
**輸出：**  

```
CertificateArn          : arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
CreatedAt               : 1/21/2016 5:55:59 PM
DomainName              : www.example.com
DomainValidationOptions : {www.example.com}
InUseBy                 : {}
IssuedAt                : 1/1/0001 12:00:00 AM
Issuer                  :
KeyAlgorithm            : RSA-2048
NotAfter                : 1/1/0001 12:00:00 AM
NotBefore               : 1/1/0001 12:00:00 AM
RevocationReason        :
RevokedAt               : 1/1/0001 12:00:00 AM
Serial                  :
SignatureAlgorithm      : SHA256WITHRSA
Status                  : PENDING_VALIDATION
Subject                 : CN=www.example.com
SubjectAlternativeNames : {www.example.net}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ACMCertificateList`
<a name="acm_ListCertificates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ACMCertificateList`。

**Tools for PowerShell V5**  
**範例 1：擷取所有憑證 ARN 的清單及其每一個的網域名稱。Cmdlet 會自動分頁以擷取所有 ARN。若要手動控制分頁，請使用 -MaxItem 參數來控制每個服務呼叫傳回多少憑證 ARN，並使用 -NextToken 參數指出每個呼叫的起點。**  

```
Get-ACMCertificateList
```
**輸出：**  

```
CertificateArn                                                                      DomainName
--------------                                                                      ----------
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012 www.example.com
```
**範例 2：擷取憑證狀態符合所提供狀態的所有憑證 ARN 清單。**  

```
Get-ACMCertificateList -CertificateStatus "VALIDATION_TIMED_OUT","FAILED"
```
**範例 3：此範例傳回 us-east-1 區域中具有 RSA\$12048 金鑰類型，以及 CODE\$1SIGNING 延伸金鑰使用方式或用途的所有憑證清單。您可以在 ListCertificates Filters API 參考主題中找到這些篩選參數的值：https://docs.aws.amazon.com/acm/latest/APIReference/API\$1Filters.html。**  

```
Get-ACMCertificateList -Region us-east-1 -Includes_KeyType RSA_2048 -Includes_ExtendedKeyUsage CODE_SIGNING
```
**輸出：**  

```
CertificateArn                                                                      DomainName                
--------------                                                                      ----------                
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-d7c0-48c1-af8d-2133d8f30zzz *.route53docs.com
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-98a5-443d-a734-800430c80zzz nerdzizm.net               
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-2be6-4376-8fa7-bad559525zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-e7ca-44c5-803e-24d9f2f36zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-1241-4b71-80b1-090305a62zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-8709-4568-8c64-f94617c99zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-a8fa-4a61-98cf-e08ccc0eezzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-fa47-40fe-a714-2d277d3eezzz *.route53docs.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListCertificates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ACMCertificate`
<a name="acm_RequestCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ACMCertificate`。

**Tools for PowerShell V5**  
**範例 1：建立新的憑證。服務會傳回新憑證的 ARN。**  

```
New-ACMCertificate -DomainName "www.example.com"
```
**輸出：**  

```
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
```
**範例 2：建立新的憑證。服務會傳回新憑證的 ARN。**  

```
New-ACMCertificate -DomainName "www.example.com" -SubjectAlternativeName "example.com","www.example.net"
```
**輸出：**  

```
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [RequestCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ACMCertificate`
<a name="acm_DeleteCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ACMCertificate`。

**Tools for PowerShell V5**  
**範例 1：刪除由提供的 ARN 和相關聯的私有金鑰所識別的憑證。在繼續之前，Cmdlet 會提示進行確認；新增 -Force 切換變數以隱藏確認。**  

```
Remove-ACMCertificate -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
+  如需 API 詳細資訊，請參閱 *AWS Tools for PowerShell Cmdlet 參考 (V5)* 中的 [DeleteCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Send-ACMValidationEmail`
<a name="acm_ResendValidationEmail_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Send-ACMValidationEmail`。

**Tools for PowerShell V5**  
**範例 1：請求傳送電子郵件以驗證 'www.example.com' 的網域擁有權。如果您 Shell 的 \$1ConfirmPreference 設定為 'Medium' 或更低，Cmdlet 會在繼續之前提示確認。新增 -Force 切換變數以隱藏確認提示。**  

```
$params = @{
    CertificateArn="arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
    Domain="www.example.com"
    ValidationDomain="example.com"    
}        
Send-ACMValidationEmail @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResendValidationEmail](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Application Auto Scaling 範例
<a name="powershell_application-auto-scaling_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Application Auto Scaling 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-AASScalableTarget`
<a name="application-auto-scaling_RegisterScalableTarget_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-AASScalableTarget`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會註冊或更新可擴展的目標。可擴展的目標是 Application Auto Scaling 可橫向擴充和縮減的資源。**  

```
Add-AASScalableTarget -ServiceNamespace AppStream -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -MinCapacity 2 -MaxCapacity 10
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterScalableTarget](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-AASScalableTarget`
<a name="application-auto-scaling_DescribeScalableTargets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-AASScalableTarget`。

**Tools for PowerShell V5**  
**範例 1：此範例將提供指定命名空間中 Application Autoscaling 可擴展目標的相關資訊。**  

```
Get-AASScalableTarget -ServiceNamespace "AppStream"
```
**輸出：**  

```
CreationTime      : 11/7/2019 2:30:03 AM
MaxCapacity       : 5
MinCapacity       : 1
ResourceId        : fleet/Test
RoleARN           : arn:aws:iam::012345678912:role/aws-service-role/appstream.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_AppStreamFleet
ScalableDimension : appstream:fleet:DesiredCapacity
ServiceNamespace  : appstream
SuspendedState    : Amazon.ApplicationAutoScaling.Model.SuspendedState
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScalableTargets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-AASScalingActivity`
<a name="application-auto-scaling_DescribeScalingActivities_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-AASScalingActivity`。

**Tools for PowerShell V5**  
**範例 1：提供過去六週內，具有指定之命名空間的擴展活動的描述性資訊。**  

```
Get-AASScalingActivity -ServiceNamespace AppStream
```
**輸出：**  

```
ActivityId        : 2827409f-b639-4cdb-a957-8055d5d07434
Cause             : monitor alarm Appstream2-MyFleet-default-scale-in-Alarm in state ALARM triggered policy default-scale-in
Description       : Setting desired capacity to 2.
Details           :
EndTime           : 12/14/2019 11:32:49 AM
ResourceId        : fleet/MyFleet
ScalableDimension : appstream:fleet:DesiredCapacity
ServiceNamespace  : appstream
StartTime         : 12/14/2019 11:32:14 AM
StatusCode        : Successful
StatusMessage     : Successfully set desired capacity to 2. Change successfully fulfilled by appstream.
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-AASScalingPolicy`
<a name="application-auto-scaling_DescribeScalingPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-AASScalingPolicy`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 描述指定之服務命名空間的 Application Auto Scaling 擴展政策。**  

```
Get-AASScalingPolicy -ServiceNamespace AppStream
```
**輸出：**  

```
Alarms                                   : {Appstream2-LabFleet-default-scale-out-Alarm}
CreationTime                             : 9/3/2019 2:48:15 AM
PolicyARN                                : arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:5659b069-b5cd-4af1-9f7f-3e956d36233e:resource/appstream/fleet/LabFleet:
                                           policyName/default-scale-out
PolicyName                               : default-scale-out
PolicyType                               : StepScaling
ResourceId                               : fleet/LabFleet
ScalableDimension                        : appstream:fleet:DesiredCapacity
ServiceNamespace                         : appstream
StepScalingPolicyConfiguration           : Amazon.ApplicationAutoScaling.Model.StepScalingPolicyConfiguration
TargetTrackingScalingPolicyConfiguration :

Alarms                                   : {Appstream2-LabFleet-default-scale-in-Alarm}
CreationTime                             : 9/3/2019 2:48:15 AM
PolicyARN                                : arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:5659b069-b5cd-4af1-9f7f-3e956d36233e:resource/appstream/fleet/LabFleet:
                                           policyName/default-scale-in
PolicyName                               : default-scale-in
PolicyType                               : StepScaling
ResourceId                               : fleet/LabFleet
ScalableDimension                        : appstream:fleet:DesiredCapacity
ServiceNamespace                         : appstream
StepScalingPolicyConfiguration           : Amazon.ApplicationAutoScaling.Model.StepScalingPolicyConfiguration
TargetTrackingScalingPolicyConfiguration :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScalingPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-AASScheduledAction`
<a name="application-auto-scaling_DescribeScheduledActions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-AASScheduledAction`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 列出為 Auto Scaling 群組排程，且尚未執行或尚未到達結束時間的動作。**  

```
Get-AASScheduledAction -ServiceNamespace AppStream
```
**輸出：**  

```
CreationTime         : 12/22/2019 9:25:52 AM
EndTime              : 1/1/0001 12:00:00 AM
ResourceId           : fleet/MyFleet
ScalableDimension    : appstream:fleet:DesiredCapacity
ScalableTargetAction : Amazon.ApplicationAutoScaling.Model.ScalableTargetAction
Schedule             : cron(0 0 8 ? * MON-FRI *)
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:012345678912:scheduledAction:4897ca24-3caa-4bf1-8484-851a089b243c:resource/appstream/fleet/MyFleet:scheduledActionName
                       /WeekDaysFleetScaling
ScheduledActionName  : WeekDaysFleetScaling
ServiceNamespace     : appstream
StartTime            : 1/1/0001 12:00:00 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-AASScalableTarget`
<a name="application-auto-scaling_DeregisterScalableTarget_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-AASScalableTarget`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會取消註冊 Application Auto Scaling 可擴展的目標。取消註冊可擴展的目標會刪除與其相關聯的擴展政策。**  

```
Remove-AASScalableTarget -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -ServiceNamespace AppStream
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-AASScalableTarget (DeregisterScalableTarget)" on target "fleet/MyFleet".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterScalableTarget](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-AASScalingPolicy`
<a name="application-auto-scaling_DeleteScalingPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-AASScalingPolicy`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會刪除 Application Auto Scaling 可擴展目標的指定擴展政策。**  

```
Remove-AASScalingPolicy -ServiceNamespace AppStream -PolicyName "default-scale-out" -ResourceId fleet/Test -ScalableDimension appstream:fleet:DesiredCapacity
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-AASScheduledAction`
<a name="application-auto-scaling_DeleteScheduledAction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-AASScheduledAction`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會刪除 Application Auto Scaling 可擴展目標的指定排程動作。**  

```
Remove-AASScheduledAction -ServiceNamespace AppStream -ScheduledActionName WeekDaysFleetScaling -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-AASScheduledAction (DeleteScheduledAction)" on target "WeekDaysFleetScaling".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-AASScalingPolicy`
<a name="application-auto-scaling_PutScalingPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-AASScalingPolicy`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會建立或更新 Application Auto Scaling 可擴展目標的政策。每個可擴展目標都由服務命名空間、資源 ID 和可擴展維度識別。**  

```
Set-AASScalingPolicy -ServiceNamespace AppStream -PolicyName ASFleetScaleInPolicy -PolicyType StepScaling  -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -StepScalingPolicyConfiguration_AdjustmentType ChangeInCapacity -StepScalingPolicyConfiguration_Cooldown 360 -StepScalingPolicyConfiguration_MetricAggregationType Average -StepScalingPolicyConfiguration_StepAdjustments @{ScalingAdjustment = -1; MetricIntervalUpperBound = 0}
```
**輸出：**  

```
Alarms    PolicyARN
------    ---------
{}        arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:4897ca24-3caa-4bf1-8484-851a089b243c:resource/appstream/fleet/MyFleet:policyName/ASFleetScaleInPolicy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-AASScheduledAction`
<a name="application-auto-scaling_PutScheduledAction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-AASScheduledAction`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會建立或更新 Application Auto Scaling 可擴展目標的排程動作。每個可擴展目標都由服務命名空間、資源 ID 和可擴展維度識別。**  

```
Set-AASScheduledAction -ServiceNamespace AppStream -ResourceId fleet/MyFleet -Schedule "cron(0 0 8 ? * MON-FRI *)" -ScalableDimension appstream:fleet:DesiredCapacity -ScheduledActionName WeekDaysFleetScaling -ScalableTargetAction_MinCapacity 5 -ScalableTargetAction_MaxCapacity 10
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 WorkSpaces 應用程式範例
<a name="powershell_appstream_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 WorkSpaces 應用程式來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-APSResourceTag`
<a name="appstream_TagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-APSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將資源標籤新增至 AppStream 資源**  

```
Add-APSResourceTag -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest -Tag @{StackState='Test'} -Select ^Tag
```
**輸出：**  

```
Name                           Value
----                           -----
StackState                     Test
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Copy-APSImage`
<a name="appstream_CopyImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Copy-APSImage`。

**Tools for PowerShell V5**  
**範例 1：此範例會將映像複製到其他區域**  

```
Copy-APSImage -DestinationImageName TestImageCopy -DestinationRegion us-west-2 -SourceImageName Powershell
```
**輸出：**  

```
TestImageCopy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CopyImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-APSUSer`
<a name="appstream_DisableUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-APSUSer`。

**Tools for PowerShell V5**  
**範例 1：此範例會停用 USERPOOL 中的使用者**  

```
Disable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-APSUser`
<a name="appstream_EnableUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-APSUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 USERPOOL 中啟用已停用的使用者**  

```
Enable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSAssociatedFleetList`
<a name="appstream_ListAssociatedFleets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSAssociatedFleetList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示與堆疊相關聯的機群**  

```
Get-APSAssociatedFleetList -StackName PowershellStack
```
**輸出：**  

```
PowershellFleet
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAssociatedFleets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSAssociatedStackList`
<a name="appstream_ListAssociatedStacks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSAssociatedStackList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示與機群相關聯的堆疊**  

```
Get-APSAssociatedStackList -FleetName PowershellFleet
```
**輸出：**  

```
PowershellStack
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAssociatedStacks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSDirectoryConfigList`
<a name="appstream_DescribeDirectoryConfigs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSDirectoryConfigList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示 AppStream 中建立的目錄組態**  

```
Get-APSDirectoryConfigList | Select DirectoryName, OrganizationalUnitDistinguishedNames, CreatedTime
```
**輸出：**  

```
DirectoryName OrganizationalUnitDistinguishedNames CreatedTime
------------- ------------------------------------ -----------
Test.com      {OU=AppStream,DC=Test,DC=com}    9/6/2019 10:56:40 AM
contoso.com   {OU=AppStream,OU=contoso,DC=contoso,DC=com}  8/9/2019 9:08:50 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDirectoryConfigs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSFleetList`
<a name="appstream_DescribeFleets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSFleetList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示機群的詳細資訊**  

```
Get-APSFleetList -Name Test
```
**輸出：**  

```
Arn                            : arn:aws:appstream:us-east-1:1234567890:fleet/Test
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 9/12/2019 5:00:45 PM
Description                    : Test
DisconnectTimeoutInSeconds     : 900
DisplayName                    : Test
DomainJoinInfo                 :
EnableDefaultInternetAccess    : False
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 900
ImageArn                       : arn:aws:appstream:us-east-1:1234567890:image/Test
ImageName                      : Test
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : Test
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeFleets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSImageBuilderList`
<a name="appstream_DescribeImageBuilders_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSImageBuilderList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示 ImageBuilder 的詳細資訊**  

```
Get-APSImageBuilderList -Name TestImage
```
**輸出：**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:1234567890:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : STOPPED
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeImageBuilders](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSImageList`
<a name="appstream_DescribeImages_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSImageList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示私有 AppStream 映像**  

```
Get-APSImageList -Type PRIVATE | select DisplayName, ImageBuilderName, Visibility, arn
```
**輸出：**  

```
DisplayName          ImageBuilderName      Visibility Arn
-----------          ----------------      ---------- ---
OfficeApps           OfficeApps            PRIVATE    arn:aws:appstream:us-east-1:123456789012:image/OfficeApps
SessionScriptV2      SessionScriptTest     PRIVATE    arn:aws:appstream:us-east-1:123456789012:image/SessionScriptV2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeImages](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSImagePermission`
<a name="appstream_DescribeImagePermissions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSImagePermission`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示共享 AppStream 映像上的映像許可**  

```
Get-APSImagePermission -Name Powershell  | select SharedAccountId, @{n="AllowFleet";e={$_.ImagePermissions.AllowFleet}}, @{n="AllowImageBuilder";e={$_.ImagePermissions.AllowImageBuilder}}
```
**輸出：**  

```
SharedAccountId AllowFleet AllowImageBuilder
--------------- ---------- -----------------
123456789012          True              True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSSessionList`
<a name="appstream_DescribeSessions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSSessionList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示機群的工作階段清單**  

```
Get-APSSessionList -FleetName PowershellFleet -StackName PowershellStack
```
**輸出：**  

```
AuthenticationType         : API
ConnectionState            : CONNECTED
FleetName                  : PowershellFleet
Id                         : d8987c70-4394-4324-a396-2d485c26f2a2
MaxExpirationTime          : 12/27/2019 4:54:07 AM
NetworkAccessConfiguration : Amazon.AppStream.Model.NetworkAccessConfiguration
StackName                  : PowershellStack
StartTime                  : 12/26/2019 12:54:12 PM
State                      : ACTIVE
UserId                     : Test
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSessions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSStackList`
<a name="appstream_DescribeStacks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSStackList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示 AppStream Stack 的清單**  

```
Get-APSStackList | Select DisplayName, Arn, CreatedTime
```
**輸出：**  

```
DisplayName                   Arn                                                                          CreatedTime
-----------                   ---                                                                          -----------
PowershellStack               arn:aws:appstream:us-east-1:123456789012:stack/PowershellStack               4/24/2019 8:49:29 AM
SessionScriptTest             arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest             9/12/2019 3:23:12 PM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSTagsForResourceList`
<a name="appstream_ListTagsForResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSTagsForResourceList`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示 AppStream 資源上的標籤**  

```
Get-APSTagsForResourceList -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest
```
**輸出：**  

```
Key        Value
---        -----
StackState Test
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSUsageReportSubscription`
<a name="appstream_DescribeUsageReportSubscriptions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSUsageReportSubscription`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示 AppStreamUsageReport 組態詳細資訊**  

```
Get-APSUsageReportSubscription
```
**輸出：**  

```
LastGeneratedReportDate S3BucketName                                   Schedule SubscriptionErrors
----------------------- ------------                                   -------- ------------------
1/1/0001 12:00:00 AM    appstream-logs-us-east-1-123456789012-sik1hnxe DAILY    {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeUsageReportSubscriptions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSUser`
<a name="appstream_DescribeUsers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSUser`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示具已啟用狀態的使用者清單**  

```
Get-APSUser -AuthenticationType USERPOOL | Select-Object UserName, AuthenticationType, Enabled
```
**輸出：**  

```
UserName                   AuthenticationType Enabled
--------                   ------------------ -------
foo1@contoso.com USERPOOL              True
foo2@contoso.com        USERPOOL              True
foo3@contoso.com    USERPOOL              True
foo4@contoso.com   USERPOOL              True
foo5@contoso.com         USERPOOL              True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeUsers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-APSUserStackAssociation`
<a name="appstream_DescribeUserStackAssociations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-APSUserStackAssociation`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示指派給堆疊的使用者清單**  

```
Get-APSUserStackAssociation -StackName PowershellStack
```
**輸出：**  

```
AuthenticationType SendEmailNotification StackName       UserName
------------------ --------------------- ---------       --------
USERPOOL           False                 PowershellStack TestUser1@lab.com
USERPOOL           False                 PowershellStack TestUser2@lab.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeUserStackAssociations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSDirectoryConfig`
<a name="appstream_CreateDirectoryConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSDirectoryConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 AppStream 中建立目錄組態**  

```
New-APSDirectoryConfig -ServiceAccountCredentials_AccountName contoso\ServiceAccount -ServiceAccountCredentials_AccountPassword MyPass -DirectoryName contoso.com -OrganizationalUnitDistinguishedName "OU=AppStream,OU=Contoso,DC=Contoso,DC=com"
```
**輸出：**  

```
CreatedTime            DirectoryName OrganizationalUnitDistinguishedNames        ServiceAccountCredentials
-----------            ------------- ------------------------------------        -------------------------
12/27/2019 11:00:30 AM contoso.com   {OU=AppStream,OU=Contoso,DC=Contoso,DC=com} Amazon.AppStream.Model.ServiceAccountCredentials
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSFleet`
<a name="appstream_CreateFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的 AppStream 機群**  

```
New-APSFleet -ComputeCapacity_DesiredInstance 1 -InstanceType stream.standard.medium -Name TestFleet -DisplayName TestFleet -FleetType ON_DEMAND -EnableDefaultInternetAccess $True -VpcConfig_SubnetIds "subnet-123ce32","subnet-a1234cfd" -VpcConfig_SecurityGroupIds sg-4d012a34 -ImageName SessionScriptTest -Region us-west-2
```
**輸出：**  

```
Arn                            : arn:aws:appstream:us-west-2:123456789012:fleet/TestFleet
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 12/27/2019 11:24:42 AM
Description                    :
DisconnectTimeoutInSeconds     : 900
DisplayName                    : TestFleet
DomainJoinInfo                 :
EnableDefaultInternetAccess    : True
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 0
ImageArn                       : arn:aws:appstream:us-west-2:123456789012:image/SessionScriptTest
ImageName                      : SessionScriptTest
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : TestFleet
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSImageBuilder`
<a name="appstream_CreateImageBuilder_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSImageBuilder`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 AppStream 中建立映像建置器**  

```
New-APSImageBuilder -InstanceType stream.standard.medium -Name TestIB -DisplayName TestIB -ImageName AppStream-WinServer2012R2-12-12-2019 -EnableDefaultInternetAccess $True -VpcConfig_SubnetId subnet-a1234cfd -VpcConfig_SecurityGroupIds sg-2d012a34 -Region us-west-2
```
**輸出：**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 12-16-2019
Arn                         : arn:aws:appstream:us-west-2:123456789012:image-builder/TestIB
CreatedTime                 : 12/27/2019 11:39:24 AM
Description                 :
DisplayName                 : TestIB
DomainJoinInfo              :
EnableDefaultInternetAccess : True
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-west-2::image/AppStream-WinServer2012R2-12-12-2019
ImageBuilderErrors          : {}
InstanceType                : stream.standard.medium
Name                        : TestIB
NetworkAccessConfiguration  :
Platform                    : WINDOWS
State                       : PENDING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSImageBuilderStreamingURL`
<a name="appstream_CreateImageBuilderStreamingURL_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSImageBuilderStreamingURL`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立 2 小時有效時間的 ImageBuilder 串流 URL**  

```
New-APSImageBuilderStreamingURL -Name TestIB -Validity 7200 -Region us-west-2
```
**輸出：**  

```
Expires               StreamingURL
-------               ------------
12/27/2019 1:49:13 PM https://appstream2.us-west-2.aws.amazon.com/authenticate?parameters=eyJ0eXBlIjoiQURNSU4iLCJleHBpcmVzIjoiMTU3NzQ1NDU1MyIsImF3c0FjY291bnRJZCI6IjM5MzQwMzgxMTQwNyIsInVzZXJJZCI6ImFkbWluIiwiY2F
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateImageBuilderStreamingURL](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSStack`
<a name="appstream_CreateStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSStack`。

**Tools for PowerShell V5**  
**範例 1：此範例建立新的 AppStream 堆疊**  

```
New-APSStack -Name TestStack -DisplayName TestStack -ApplicationSettings_Enabled $True -ApplicationSettings_SettingsGroup TestStack -Region us-west-2
```
**輸出：**  

```
AccessEndpoints     : {}
ApplicationSettings : Amazon.AppStream.Model.ApplicationSettingsResponse
Arn                 : arn:aws:appstream:us-west-2:123456789012:stack/TestStack
CreatedTime         : 12/27/2019 12:34:19 PM
Description         :
DisplayName         : TestStack
EmbedHostDomains    : {}
FeedbackURL         :
Name                : TestStack
RedirectURL         :
StackErrors         : {}
StorageConnectors   : {}
UserSettings        : {Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSStreamingURL`
<a name="appstream_CreateStreamingURL_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSStreamingURL`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立堆疊的串流 URL**  

```
New-APSStreamingURL -StackName SessionScriptTest -FleetName SessionScriptNew -UserId TestUser
```
**輸出：**  

```
Expires                StreamingURL
-------                ------------
12/27/2019 12:43:37 PM https://appstream2.us-east-1.aws.amazon.com/authenticate?parameters=eyJ0eXBlIjoiRU5EX1VTRVIiLCJleHBpcmVzIjoiMTU3NzQ1MDYxNyIsImF3c0FjY291bnRJZCI6IjM5MzQwMzgxMTQwNyIsInVzZXJJZCI6IlRlc3RVc2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateStreamingURL](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSUsageReportSubscription`
<a name="appstream_CreateUsageReportSubscription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSUsageReportSubscription`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用 AppStream 用量報告**  

```
New-APSUsageReportSubscription
```
**輸出：**  

```
S3BucketName                                   Schedule
------------                                   --------
appstream-logs-us-east-1-123456789012-sik2hnxe DAILY
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateUsageReportSubscription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-APSUser`
<a name="appstream_CreateUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-APSUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 USERPOOL 中建立使用者**  

```
New-APSUser -UserName Test@lab.com -AuthenticationType USERPOOL -FirstName 'kt' -LastName 'aws' -Select ^UserName
```
**輸出：**  

```
Test@lab.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-APSFleet`
<a name="appstream_AssociateFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-APSFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會向堆疊註冊機群**  

```
Register-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssociateFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-APSUserStackBatch`
<a name="appstream_BatchAssociateUserStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-APSUserStackBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會將堆疊指派給 USERPOOL 中的使用者**  

```
Register-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchAssociateUserStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSDirectoryConfig`
<a name="appstream_DeleteDirectoryConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSDirectoryConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除 AppStream Directory 組態**  

```
Remove-APSDirectoryConfig -DirectoryName contoso.com
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSDirectoryConfig (DeleteDirectoryConfig)" on target "contoso.com".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSFleet`
<a name="appstream_DeleteFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 AppStream 機群**  

```
Remove-APSFleet -Name TestFleet -Region us-west-2
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSFleet (DeleteFleet)" on target "TestFleet".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSImage`
<a name="appstream_DeleteImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSImage`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除映像**  

```
Remove-APSImage -Name TestImage -Region us-west-2
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImage (DeleteImage)" on target "TestImage".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A

Applications                : {}
AppstreamAgentVersion       : LATEST
Arn                         : arn:aws:appstream:us-west-2:123456789012:image/TestImage
BaseImageArn                :
CreatedTime                 : 12/27/2019 1:34:10 PM
Description                 :
DisplayName                 : TestImage
ImageBuilderName            :
ImageBuilderSupported       : True
ImagePermissions            :
Name                        : TestImage
Platform                    : WINDOWS
PublicBaseImageReleasedDate : 6/12/2018 12:00:00 AM
State                       : AVAILABLE
StateChangeReason           :
Visibility                  : PRIVATE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSImageBuilder`
<a name="appstream_DeleteImageBuilder_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSImageBuilder`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 ImageBuilder**  

```
Remove-APSImageBuilder -Name TestIB -Region us-west-2
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImageBuilder (DeleteImageBuilder)" on target "TestIB".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A

AccessEndpoints             : {}
AppstreamAgentVersion       : 12-16-2019
Arn                         : arn:aws:appstream:us-west-2:123456789012:image-builder/TestIB
CreatedTime                 : 12/27/2019 11:39:24 AM
Description                 :
DisplayName                 : TestIB
DomainJoinInfo              :
EnableDefaultInternetAccess : True
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-west-2::image/AppStream-WinServer2012R2-12-12-2019
ImageBuilderErrors          : {}
InstanceType                : stream.standard.medium
Name                        : TestIB
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : DELETING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSImagePermission`
<a name="appstream_DeleteImagePermissions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSImagePermission`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除映像的許可**  

```
Remove-APSImagePermission -Name Powershell -SharedAccountId 123456789012
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImagePermission (DeleteImagePermissions)" on target "Powershell".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSResourceTag`
<a name="appstream_UntagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會從 AppStream 資源移除資源標籤**  

```
Remove-APSResourceTag -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest -TagKey StackState
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSResourceTag (UntagResource)" on target "arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSStack`
<a name="appstream_DeleteStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSStack`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除堆疊**  

```
Remove-APSStack -Name TestStack -Region us-west-2
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSStack (DeleteStack)" on target "TestStack".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSUsageReportSubscription`
<a name="appstream_DeleteUsageReportSubscription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSUsageReportSubscription`。

**Tools for PowerShell V5**  
**範例 1：此範例會停用 AppStream 用量報告訂閱**  

```
Remove-APSUsageReportSubscription
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSUsageReportSubscription (DeleteUsageReportSubscription)" on target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteUsageReportSubscription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-APSUser`
<a name="appstream_DeleteUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-APSUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會從 USERPOOL 刪除使用者**  

```
Remove-APSUser -UserName TestUser@lab.com -AuthenticationType USERPOOL
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSUser (DeleteUser)" on target "TestUser@lab.com".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Revoke-APSSession`
<a name="appstream_ExpireSession_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Revoke-APSSession`。

**Tools for PowerShell V5**  
**範例 1：此範例會撤銷 AppStream 機群的工作階段**  

```
Revoke-APSSession -SessionId 6cd2f9a3-f948-4aa1-8014-8a7dcde14877
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ExpireSession](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-APSFleet`
<a name="appstream_StartFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-APSFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟動機群**  

```
Start-APSFleet -Name PowershellFleet
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-APSImageBuilder`
<a name="appstream_StartImageBuilder_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-APSImageBuilder`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟動 ImageBuilder**  

```
Start-APSImageBuilder -Name TestImage
```
**輸出：**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:123456789012:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : PENDING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-APSFleet`
<a name="appstream_StopFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-APSFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會停止機群**  

```
Stop-APSFleet -Name PowershellFleet
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-APSImageBuilder`
<a name="appstream_StopImageBuilder_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-APSImageBuilder`。

**Tools for PowerShell V5**  
**範例 1：此範例會停止 ImageBuilder**  

```
Stop-APSImageBuilder -Name TestImage
```
**輸出：**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:123456789012:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : STOPPING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-APSFleet`
<a name="appstream_DisassociateFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-APSFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會從堆疊取消註冊機群**  

```
Unregister-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisassociateFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-APSUserStackBatch`
<a name="appstream_BatchDisassociateUserStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-APSUserStackBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指派的堆疊移除使用者**  

```
Unregister-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchDisassociateUserStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-APSDirectoryConfig`
<a name="appstream_UpdateDirectoryConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-APSDirectoryConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新在 AppStream 中建立的目錄組態**  

```
Update-APSDirectoryConfig -ServiceAccountCredentials_AccountName contoso\ServiceAccount -ServiceAccountCredentials_AccountPassword MyPass@1$@# -DirectoryName contoso.com -OrganizationalUnitDistinguishedName "OU=AppStreamNew,OU=Contoso,DC=Contoso,DC=com"
```
**輸出：**  

```
CreatedTime           DirectoryName OrganizationalUnitDistinguishedNames           ServiceAccountCredentials
-----------           ------------- ------------------------------------           -------------------------
12/27/2019 3:50:02 PM contoso.com   {OU=AppStreamNew,OU=Contoso,DC=Contoso,DC=com} Amazon.AppStream.Model.ServiceAccountCredentials
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-APSFleet`
<a name="appstream_UpdateFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-APSFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新機群的屬性**  

```
Update-APSFleet -Name PowershellFleet -EnableDefaultInternetAccess $True -DisconnectTimeoutInSecond 950
```
**輸出：**  

```
Arn                            : arn:aws:appstream:us-east-1:123456789012:fleet/PowershellFleet
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 4/24/2019 8:39:41 AM
Description                    : PowershellFleet
DisconnectTimeoutInSeconds     : 950
DisplayName                    : PowershellFleet
DomainJoinInfo                 :
EnableDefaultInternetAccess    : True
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 900
ImageArn                       : arn:aws:appstream:us-east-1:123456789012:image/Powershell
ImageName                      : Powershell
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : PowershellFleet
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-APSImagePermission`
<a name="appstream_UpdateImagePermissions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-APSImagePermission`。

**Tools for PowerShell V5**  
**範例 1：此範例會與其他帳戶共用 AppStream 映像**  

```
Update-APSImagePermission -Name Powershell -SharedAccountId 123456789012 -ImagePermissions_AllowFleet $True -ImagePermissions_AllowImageBuilder $True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-APSStack`
<a name="appstream_UpdateStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-APSStack`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新 (啟用) 堆疊上的應用程式設定持續性和主資料夾**  

```
Update-APSStack -Name PowershellStack -ApplicationSettings_Enabled $True -ApplicationSettings_SettingsGroup PowershellStack -StorageConnector @{ConnectorType="HOMEFOLDERS"}
```
**輸出：**  

```
AccessEndpoints     : {}
ApplicationSettings : Amazon.AppStream.Model.ApplicationSettingsResponse
Arn                 : arn:aws:appstream:us-east-1:123456789012:stack/PowershellStack
CreatedTime         : 4/24/2019 8:49:29 AM
Description         : PowershellStack
DisplayName         : PowershellStack
EmbedHostDomains    : {}
FeedbackURL         :
Name                : PowershellStack
RedirectURL         :
StackErrors         : {}
StorageConnectors   : {Amazon.AppStream.Model.StorageConnector, Amazon.AppStream.Model.StorageConnector}
UserSettings        : {Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Aurora 範例
<a name="powershell_aurora_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Aurora 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-RDSOrderableDBInstanceOption`
<a name="aurora_DescribeOrderableDBInstanceOptions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RDSOrderableDBInstanceOption`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了支援 AWS 區域中特定資料庫執行個體類別的資料庫引擎版本。**  

```
$params = @{
  Engine = 'aurora-postgresql'
  DBInstanceClass = 'db.r5.large'
  Region = 'us-east-1'
}
Get-RDSOrderableDBInstanceOption @params
```
**範例 2：此範例列出 AWS 區域中特定資料庫引擎版本支援的資料庫執行個體類別。**  

```
$params = @{
  Engine = 'aurora-postgresql'
  EngineVersion = '13.6'
  Region = 'us-east-1'
}
Get-RDSOrderableDBInstanceOption @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Auto Scaling 範例
<a name="powershell_auto-scaling_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Auto Scaling 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-ASLoadBalancer`
<a name="auto-scaling_AttachLoadBalancers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-ASLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的負載平衡器連接至指定的 Auto Scaling 群組。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Complete-ASLifecycleAction`
<a name="auto-scaling_CompleteLifecycleAction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Complete-ASLifecycleAction`。

**Tools for PowerShell V5**  
**範例 1：此範例會完成指定的生命週期動作。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-ASMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-ASMetricsCollection`。

**Tools for PowerShell V5**  
**範例 1：此範例停用指定的 Auto Scaling 群組的指定指標監控功能。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**範例 2：此範例停用指定的 Auto Scaling 群組的所有指標監控功能。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Dismount-ASInstance`
<a name="auto-scaling_DetachInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Dismount-ASInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的執行個體與指定的 Auto Scaling 群組分開，並減少所需的容量，如此 Auto Scaling 就不會啟動替代執行個體。**  

```
Dismount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**輸出：**  

```
ActivityId           : 06733445-ce94-4039-be1b-b9f1866e276e
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-93633f9b was detached in response to a user request, shrinking
                       the capacity from 2 to 1.
Description          : Detaching EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
**範例 2：此範例將指定的執行個體與指定的 Auto Scaling 群組分開，而不會減少所需的容量。Auto Scaling 會啟動替代執行個體。**  

```
Dismount-ASInstance -InstanceId i-7bf746a2 -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**輸出：**  

```
ActivityId           : f43a3cd4-d38c-4af7-9fe0-d76ec2307b6d
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-7bf746a2 was detached in response to a user request.
Description          : Detaching EC2 instance: i-7bf746a2
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DetachInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Dismount-ASLoadBalancer`
<a name="auto-scaling_DetachLoadBalancers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Dismount-ASLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的負載平衡器與指定的 Auto Scaling 群組分開。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-ASMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-ASMetricsCollection`。

**Tools for PowerShell V5**  
**範例 1：此範例啟用指定的 Auto Scaling 群組的指定指標監控功能。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**範例 2：此範例監控指定的 Auto Scaling 群組的所有指標監控功能。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enter-ASStandby`
<a name="auto-scaling_EnterStandby_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enter-ASStandby`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的執行個體置於待命模式，並減少所需的容量，如此 Auto Scaling 就不會啟動替代執行個體。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**輸出：**  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request,
                       shrinking the capacity from 2 to 1.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
**範例 2：此範例將指定的執行個體置於待命模式，而不會減少所需的容量。Auto Scaling 會啟動替代執行個體。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**輸出：**  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnterStandby](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Exit-ASStandby`
<a name="auto-scaling_ExitStandby_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Exit-ASStandby`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的執行個體移出待命模式。**  

```
Exit-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
**輸出：**  

```
ActivityId           : 1833d3e8-e32f-454e-b731-0670ad4c6934
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:51:21Z instance i-95b8484f was moved out of standby in response to a user 
                       request, increasing the capacity from 1 to 2.
Description          : Moving EC2 instance out of Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 30
StartTime            : 11/22/2015 7:51:21 AM
StatusCode           : PreInService
StatusMessage        :
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [ExitStandby](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASAccountLimit`
<a name="auto-scaling_DescribeAccountLimits_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASAccountLimit`。

**Tools for PowerShell V5**  
**範例 1：此範例說明您 AWS 帳戶的 Auto Scaling 資源限制。**  

```
Get-ASAccountLimit
```
**輸出：**  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASAdjustmentType`
<a name="auto-scaling_DescribeAdjustmentTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASAdjustmentType`。

**Tools for PowerShell V5**  
**範例 1：此範例描述 Auto Scaling 支援的調整類型。**  

```
Get-ASAdjustmentType
```
**輸出：**  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASAutoScalingGroup`
<a name="auto-scaling_DescribeAutoScalingGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASAutoScalingGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例列出 Auto Scaling 群組的名稱。**  

```
Get-ASAutoScalingGroup | format-table -property AutoScalingGroupName
```
**輸出：**  

```
AutoScalingGroupName
--------------------
my-asg-1
my-asg-2
my-asg-3
my-asg-4
my-asg-5
my-asg-6
```
**範例 2：此範例描述指定的 Auto Scaling 群組。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1
```
**輸出：**  

```
AutoScalingGroupARN     : arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480
                          f03:autoScalingGroupName/my-asg-1
AutoScalingGroupName    : my-asg-1
AvailabilityZones       : {us-west-2b, us-west-2a}
CreatedTime             : 3/1/2015 9:05:31 AM
DefaultCooldown         : 300
DesiredCapacity         : 2
EnabledMetrics          : {}
HealthCheckGracePeriod  : 300
HealthCheckType         : EC2
Instances               : {my-lc}
LaunchConfigurationName : my-lc
LoadBalancerNames       : {}
MaxSize                 : 0
MinSize                 : 0
PlacementGroup          :
Status                  :
SuspendedProcesses      : {}
Tags                    : {}
TerminationPolicies     : {Default}
VPCZoneIdentifier       : subnet-e4f33493,subnet-5264e837
```
**範例 3：此範例描述指定的兩個 Auto Scaling 群組。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**範例 4：此範例描述指定之 Auto Scaling 群組的 Auto Scaling 執行個體。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**範例 5：此範例描述所有 Auto Scaling 群組。**  

```
Get-ASAutoScalingGroup
```
**範例 6：此範例描述指定的 Auto Scaling 群組的 LaunchTemplate。此範例假設「執行個體購買選項」設定為「依循啟動範本」。如果此選項設定為「結合購買選項和執行個體類型」，則可使用 "MixedInstancesPolicy.LaunchTemplate" 屬性存取 LaunchTemplate。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-ag-1).LaunchTemplate
```
**輸出：**  

```
LaunchTemplateId     LaunchTemplateName   Version
----------------     ------------------   -------
lt-06095fd619cb40371 test-launch-template $Default
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASAutoScalingInstance`
<a name="auto-scaling_DescribeAutoScalingInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASAutoScalingInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例列出 Auto Scaling 執行個體的 ID。**  

```
Get-ASAutoScalingInstance | format-table -property InstanceId
```
**輸出：**  

```
InstanceId
----------
i-12345678
i-87654321
i-abcd1234
```
**範例 2：此範例描述指定的 Auto Scaling 執行個體。**  

```
Get-ASAutoScalingInstance -InstanceId i-12345678
```
**輸出：**  

```
AutoScalingGroupName    : my-asg
AvailabilityZone        : us-west-2b
HealthStatus            : HEALTHY
InstanceId              : i-12345678
LaunchConfigurationName : my-lc
LifecycleState          : InService
```
**範例 3：此範例描述指定的兩個 Auto Scaling 執行個體。**  

```
Get-ASAutoScalingInstance -InstanceId @("i-12345678", "i-87654321")
```
**範例 4：此範例描述指定之 Auto Scaling 群組的 Auto Scaling 執行個體。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**範例 5：此範例描述所有 Auto Scaling 執行個體。**  

```
Get-ASAutoScalingInstance
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASAutoScalingNotificationType`
<a name="auto-scaling_DescribeAutoScalingNotificationTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASAutoScalingNotificationType`。

**Tools for PowerShell V5**  
**範例 1：此範例列出 Auto Scaling 支援的通知類型。**  

```
Get-ASAutoScalingNotificationType
```
**輸出：**  

```
autoscaling:EC2_INSTANCE_LAUNCH
autoscaling:EC2_INSTANCE_LAUNCH_ERROR
autoscaling:EC2_INSTANCE_TERMINATE
autoscaling:EC2_INSTANCE_TERMINATE_ERROR
autoscaling:TEST_NOTIFICATION
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASLaunchConfiguration`
<a name="auto-scaling_DescribeLaunchConfigurations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASLaunchConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例列出啟動組態的名稱。**  

```
Get-ASLaunchConfiguration | format-table -property LaunchConfigurationName
```
**輸出：**  

```
LaunchConfigurationName
-----------------------
my-lc-1
my-lc-2
my-lc-3
my-lc-4
my-lc-5
```
**範例 2：此範例描述指定的啟動組態。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName my-lc-1
```
**輸出：**  

```
AssociatePublicIpAddress     : True
BlockDeviceMappings          : {/dev/xvda}
ClassicLinkVPCId             :
ClassicLinkVPCSecurityGroups : {}
CreatedTime                  : 12/12/2014 3:22:08 PM
EbsOptimized                 : False
IamInstanceProfile           :
ImageId                      : ami-043a5034
InstanceMonitoring           : Amazon.AutoScaling.Model.InstanceMonitoring
InstanceType                 : t2.micro
KernelId                     :
KeyName                      : 
LaunchConfigurationARN       : arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:7e5f31e4-693b-4604-9322-
                               e6f68d7fafad:launchConfigurationName/my-lc-1
LaunchConfigurationName      : my-lc-1
PlacementTenancy             :
RamdiskId                    :
SecurityGroups               : {sg-67ef0308}
SpotPrice                    :
UserData                     :
```
**範例 3：此範例描述指定的兩個啟動組態。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName @("my-lc-1", "my-lc-2")
```
**範例 4：此範例描述所有啟動組態。**  

```
Get-ASLaunchConfiguration
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASLifecycleHook`
<a name="auto-scaling_DescribeLifecycleHooks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASLifecycleHook`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 lifecycle hook。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**輸出：**  

```
AutoScalingGroupName  : my-asg
DefaultResult         : ABANDON
GlobalTimeout         : 172800
HeartbeatTimeout      : 3600
LifecycleHookName     : myLifecycleHook
LifecycleTransition   : auto-scaling:EC2_INSTANCE_LAUNCHING
NotificationMetadata  :
NotificationTargetARN : arn:aws:sns:us-west-2:123456789012:my-topic
RoleARN               : arn:aws:iam::123456789012:role/my-iam-role
```
**範例 2：此範例描述指定的 Auto Scaling 群組的 lifecycle hook。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**範例 3：此範例描述所有 Auto Scaling 群組的所有 lifecycle hook。**  

```
Get-ASLifecycleHook
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASLifecycleHookType`
<a name="auto-scaling_DescribeLifecycleHookTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASLifecycleHookType`。

**Tools for PowerShell V5**  
**範例 1：此範例列出 Auto Scaling 支援的 lifecycle hook 類型。**  

```
Get-ASLifecycleHookType
```
**輸出：**  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASLoadBalancer`
<a name="auto-scaling_DescribeLoadBalancers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 Auto Scaling 群組的負載平衡器。**  

```
Get-ASLoadBalancer -AutoScalingGroupName my-asg
```
**輸出：**  

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASMetricCollectionType`
<a name="auto-scaling_DescribeMetricCollectionTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASMetricCollectionType`。

**Tools for PowerShell V5**  
**範例 1：此範例列出 Auto Scaling 支援的指標收集類型。**  

```
(Get-ASMetricCollectionType).Metrics
```
**輸出：**  

```
Metric
------
GroupMinSize
GroupMaxSize
GroupDesiredCapacity
GroupInServiceInstances
GroupPendingInstances
GroupTerminatingInstances
GroupStandbyInstances
GroupTotalInstances
```
**範例 2：此範例列出對應的精細程度。**  

```
(Get-ASMetricCollectionType).Granularities
```
**輸出：**  

```
Granularity
-----------
1Minute
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASNotificationConfiguration`
<a name="auto-scaling_DescribeNotificationConfigurations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASNotificationConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例描述與指定的 Auto Scaling 群組相關聯的通知動作。**  

```
Get-ASNotificationConfiguration -AutoScalingGroupName my-asg | format-list
```
**輸出：**  

```
AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_LAUNCH
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic

AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_TERMINATE
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic
```
**範例 2：此範例描述與所有 Auto Scaling 群組相關聯的通知動作。**  

```
Get-ASNotificationConfiguration
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASPolicy`
<a name="auto-scaling_DescribePolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 Auto Scaling 群組的所有政策。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg
```
**輸出：**  

```
AdjustmentType          : ChangeInCapacity
Alarms                  : {}
AutoScalingGroupName    : my-asg
Cooldown                : 0
EstimatedInstanceWarmup : 0
MetricAggregationType   :
MinAdjustmentMagnitude  : 0
MinAdjustmentStep       : 0
PolicyARN               : arn:aws:auto-scaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef
                          :autoScalingGroupName/my-asg:policyName/myScaleInPolicy
PolicyName              : myScaleInPolicy
PolicyType              : SimpleScaling
ScalingAdjustment       : -1
StepAdjustments         : {}
```
**範例 2：此範例描述指定的 Auto Scaling 群組的指定政策。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**範例 3：此範例描述所有 Auto Scaling 群組的所有政策。**  

```
Get-ASPolicy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribePolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASScalingActivity`
<a name="auto-scaling_DescribeScalingActivities_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASScalingActivity`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 Auto Scaling 群組過去六週的擴展活動。**  

```
Get-ASScalingActivity -AutoScalingGroupName my-asg
```
**輸出：**  

```
ActivityId           : 063308ae-aa22-4a9b-94f4-9fae4EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:45:16Z a user request explicitly set group desired capacity changing the desired
                       capacity from 1 to 2.  At 2015-11-22T15:45:34Z an instance was started in response to a difference
                       between desired and actual capacity, increasing the capacity from 1 to 2.
Description          : Launching a new EC2 instance: i-26e715fc
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/22/2015 7:46:09 AM
Progress             : 100
StartTime            : 11/22/2015 7:45:35 AM
StatusCode           : Successful
StatusMessage        :

ActivityId           : ce719997-086d-4c73-a2f1-ab703EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:57:53Z a user request created an AutoScalingGroup changing the desired capacity
                        from 0 to 1.  At 2015-11-20T22:57:58Z an instance was started in response to a difference betwe
                       en desired and actual capacity, increasing the capacity from 0 to 1.
Description          : Launching a new EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/20/2015 2:58:32 PM
Progress             : 100
StartTime            : 11/20/2015 2:57:59 PM
StatusCode           : Successful
StatusMessage        :
```
**範例 2：此範例描述指定的擴展活動。**  

```
Get-ASScalingActivity -ActivityId "063308ae-aa22-4a9b-94f4-9fae4EXAMPLE"
```
**範例 3：此範例描述所有 Auto Scaling 群組過去六週的擴展活動。**  

```
Get-ASScalingActivity
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASScalingProcessType`
<a name="auto-scaling_DescribeScalingProcessTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASScalingProcessType`。

**Tools for PowerShell V5**  
**範例 1：此範例列出 Auto Scaling 支援的程序類型。**  

```
Get-ASScalingProcessType
```
**輸出：**  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASScheduledAction`
<a name="auto-scaling_DescribeScheduledActions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASScheduledAction`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 Auto Scaling 群組的排程擴展動作。**  

```
Get-ASScheduledAction -AutoScalingGroupName my-asg
```
**輸出：**  

```
AutoScalingGroupName : my-asg
DesiredCapacity      : 10
EndTime              : 
MaxSize              : 
MinSize              : 
Recurrence           :
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8a4c5f24-6ec6-4306-a2dd-f7
                       2c3af3a4d6:autoScalingGroupName/my-asg:scheduledActionName/myScheduledAction
ScheduledActionName  : myScheduledAction
StartTime            : 11/30/2015 8:00:00 AM
Time                 : 11/30/2015 8:00:00 AM
```
**範例 2：此範例描述指定的排程擴展動作。**  

```
Get-ASScheduledAction -ScheduledActionName @("myScheduledScaleOut", "myScheduledScaleIn")
```
**範例 3：此範例描述在指定時間開始的排程擴展動作。**  

```
Get-ASScheduledAction -StartTime "2015-12-01T08:00:00Z"
```
**範例 4：此範例描述在指定時間結束的排程擴展動作。**  

```
Get-ASScheduledAction -EndTime "2015-12-30T08:00:00Z"
```
**範例 5：此範例描述所有 Auto Scaling 群組的排程擴展動作。**  

```
Get-ASScheduledAction
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASTag`
<a name="auto-scaling_DescribeTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASTag`。

**Tools for PowerShell V5**  
**範例 1：此範例描述鍵值為 'myTag' 或 'myTag2' 的標籤。篩選條件名稱的可能值為 'auto-scaling-group'、'key'、'value' 和 'propagate-at-launch'。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
Get-ASTag -Filter @( @{ Name="key"; Values=@("myTag", "myTag2") } )
```
**輸出：**  

```
Key               : myTag2
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue2

Key               : myTag
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立每個篩選條件參數的篩選條件。**  

```
$keys = New-Object string[] 2
$keys[0] = "myTag"
$keys[1] = "myTag2"
$filter = New-Object Amazon.AutoScaling.Model.Filter
$filter.Name = "key"
$filter.Values = $keys
Get-ASTag -Filter @( $filter )
```
**範例 3：此範例描述所有 Auto Scaling 群組的所有標籤。**  

```
Get-ASTag
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASTerminationPolicyType`
<a name="auto-scaling_DescribeTerminationPolicyTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASTerminationPolicyType`。

**Tools for PowerShell V5**  
**範例 1：此範例列出 Auto Scaling 支援的終止政策。**  

```
Get-ASTerminationPolicyType
```
**輸出：**  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Mount-ASInstance`
<a name="auto-scaling_AttachInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Mount-ASInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的執行個體連接至指定的 Auto Scaling 群組。Auto Scaling 會自動增加 Auto Scaling 群組所需的容量。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [AttachInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ASAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ASAutoScalingGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例使用指定的名稱及屬性建立 Auto Scaling 群組。預設所需容量為大小下限。因此，此 Auto Scaling 群組會啟動兩個執行個體，其中一個位於指定的兩個可用區域中。**  

```
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ASLaunchConfiguration`
<a name="auto-scaling_CreateLaunchConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ASLaunchConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例建立名為 'my-lc' 的啟動組態。使用此啟動組態的 Auto Scaling 群組啟動的 EC2 執行個體，會使用指定的執行個體類型、AMI、安全群組和 IAM 角色。**  

```
New-ASLaunchConfiguration -LaunchConfigurationName my-lc -InstanceType "m3.medium" -ImageId "ami-12345678" -SecurityGroup "sg-12345678" -IamInstanceProfile "myIamRole"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ASAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ASAutoScalingGroup`。

**Tools for PowerShell V5**  
**範例 1：如果沒有執行中的執行個體，此範例會刪除指定的 Auto Scaling 群組。在繼續操作之前，系統會提示您確認。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASAutoScalingGroup (DeleteAutoScalingGroup)" on Target "my-asg".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：如果您指定強制參數，在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force
```
**範例 3：此範例會刪除指定的 Auto Scaling 群組，並終止其包含的任何執行中執行個體。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ASLaunchConfiguration`
<a name="auto-scaling_DeleteLaunchConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ASLaunchConfiguration`。

**Tools for PowerShell V5**  
**範例 1：如果未連接至 Auto Scaling 群組，此範例會刪除指定的啟動組態。在繼續操作之前，系統會提示您確認。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLaunchConfiguration (DeleteLaunchConfiguration)" on Target "my-lc".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：如果您指定強制參數，在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ASLifecycleHook`
<a name="auto-scaling_DeleteLifecycleHook_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ASLifecycleHook`。

**Tools for PowerShell V5**  
**範例 1：此範例刪除指定 Auto Scaling 群組的指定 lifecycle hook。在繼續操作之前，系統會提示您確認。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLifecycleHook (DeleteLifecycleHook)" on Target "myLifecycleHook".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：如果您指定強制參數，在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ASNotificationConfiguration`
<a name="auto-scaling_DeleteNotificationConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ASNotificationConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的通知動作。在繼續操作之前，系統會提示您確認。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASNotificationConfiguration (DeleteNotificationConfiguration)" on Target
"arn:aws:sns:us-west-2:123456789012:my-topic".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：如果您指定強制參數，在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic" -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ASPolicy`
<a name="auto-scaling_DeletePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ASPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定之 Auto Scaling 群組的指定政策。在繼續操作之前，系統會提示您確認。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASPolicy (DeletePolicy)" on Target "myScaleInPolicy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：如果您指定強制參數，在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ASScheduledAction`
<a name="auto-scaling_DeleteScheduledAction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ASScheduledAction`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定 Auto Scaling 群組的指定排程動作。在繼續操作之前，系統會提示您確認。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASScheduledAction (DeleteScheduledAction)" on Target "myScheduledAction".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：如果您指定強制參數，在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction" -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ASTag`
<a name="auto-scaling_DeleteTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ASTag`。

**Tools for PowerShell V5**  
**範例 1：此範例從指定的 Auto Scaling 群組中移除指定的標籤。在繼續操作之前，系統會提示您確認。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } )
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ASTag (DeleteTags)" on target "Amazon.AutoScaling.Model.Tag".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：如果您指定強制參數，在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } ) -Force
```
**範例 3：使用 Powershell 版本 2 時，必須使用 New-Object 來建立 Tag 參數的標籤。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg"
$tag.Key = "myTag"
Remove-ASTag -Tag $tag -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Resume-ASProcess`
<a name="auto-scaling_ResumeProcesses_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Resume-ASProcess`。

**Tools for PowerShell V5**  
**範例 1：此範例恢復指定的 Auto Scaling 群組的指定 Auto Scaling 程序。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**範例 2：此範例恢復指定的 Auto Scaling 群組的所有暫停 Auto Scaling 處理程序。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResumeProcesses](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ASDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ASDesiredCapacity`。

**Tools for PowerShell V5**  
**範例 1：此範例設定指定的 Auto Scaling 群組的大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**範例 2：此範例設定指定 Auto Scaling 群組的大小，並等待冷卻時間告一段落，然後再擴展到新的大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ASInstanceHealth`
<a name="auto-scaling_SetInstanceHealth_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ASInstanceHealth`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定之執行個體的狀態設定為「運作狀態不良」，使其停止服務。Auto Scaling 會終止並取代執行個體。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**範例 2：此範例將指定之執行個體的狀態設定為「運作狀態良好」，使其保持服務中狀態。Auto Scaling 群組的運作狀態檢查寬限期未遵循。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ASInstanceProtection`
<a name="auto-scaling_SetInstanceProtection_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ASInstanceProtection`。

**Tools for PowerShell V5**  
**範例 1：此範例啟用指定之執行個體的執行個體保護功能。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $true
```
**範例 2：此範例停用指定之執行個體的執行個體保護功能。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetInstanceProtection](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ASTag`
<a name="auto-scaling_CreateOrUpdateTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ASTag`。

**Tools for PowerShell V5**  
**範例 1：此範例將單一標籤新增至指定的 Auto Scaling 群組。標籤索引鍵為 'myTag'，標籤值為 'myTagValue'。Auto Scaling 會將此標籤傳播到 Auto Scaling 群組啟動的後續 EC2 執行個體。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
Set-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag"; Value="myTagValue"; PropagateAtLaunch=$true} )
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立 Tag 參數的標籤。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg" 
$tag.Key = "myTag" 
$tag.Value = "myTagValue"
$tag.PropagateAtLaunch = $true
Set-ASTag -Tag $tag
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-ASPolicy`
<a name="auto-scaling_ExecutePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-ASPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例為指定的 Auto Scaling 群組執行指定的政策。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**範例 2：此範例在等待冷卻時間告一段落之後，為指定的 Auto Scaling 群組執行指定的政策。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [ExecutePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-ASInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-ASInstanceInAutoScalingGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例終止了指定的執行個體，並減少其 Auto Scaling 群組所需的容量，如此 Auto Scaling 就不會啟動替代執行個體。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $true
```
**輸出：**  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request, shrinking the capacity from 2 to 1.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
**範例 2：此範例終止了指定的執行個體，但未減少其 Auto Scaling 群組所需的容量。Auto Scaling 會啟動替代執行個體。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $false
```
**輸出：**  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Suspend-ASProcess`
<a name="auto-scaling_SuspendProcesses_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Suspend-ASProcess`。

**Tools for PowerShell V5**  
**範例 1：此範例暫停指定的 Auto Scaling 群組的指定 Auto Scaling 處理程序。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**範例 2：此範例暫停指定的 Auto Scaling 群組的所有 Auto Scaling 處理程序。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SuspendProcesses](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-ASAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-ASAutoScalingGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例更新指定的 Auto Scaling 群組的大小下限和上限。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**範例 2：此範例更新指定的 Auto Scaling 群組的預設冷卻時間。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**範例 3：此範例更新指定的 Auto Scaling 群組的可用區域。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**範例 4：此範例更新指定的 Auto Scaling 群組，使用 Elastic Load Balancing 運作狀態檢查。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-ASLifecycleActionHeartbeat`
<a name="auto-scaling_RecordLifecycleActionHeartbeat_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-ASLifecycleActionHeartbeat`。

**Tools for PowerShell V5**  
**範例 1：此範例記錄指定的生命週期動作的活動訊號。這會使執行個體保持待定狀態，直到您完成自訂動作為止。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-ASLifecycleHook`
<a name="auto-scaling_PutLifecycleHook_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-ASLifecycleHook`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的 lifecycle hook 新增至指定的 Auto Scaling 群組。**  

```
Write-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName "myLifecycleHook" -LifecycleTransition "autoscaling:EC2_INSTANCE_LAUNCHING" -NotificationTargetARN "arn:aws:sns:us-west-2:123456789012:my-sns-topic" -RoleARN "arn:aws:iam::123456789012:role/my-iam-role"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-ASNotificationConfiguration`
<a name="auto-scaling_PutNotificationConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-ASNotificationConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的 Auto Scaling 群組設定為在啟動 EC2 執行個體時，傳送通知至指定的 SNS 主題。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType "autoscaling:EC2_INSTANCE_LAUNCH" -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**範例 2：此範例將指定的 Auto Scaling 群組設定為在啟動或終止 EC2 執行個體時，傳送通知至指定的 SNS 主題。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType @("autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_TERMINATE") -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-ASScalingPolicy`
<a name="auto-scaling_PutScalingPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-ASScalingPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的政策新增至指定的 Auto Scaling 群組。指定的調整類 型決定如何解譯 ScalingAdjustment 參數。使用 'ChangeInCapacity' 時，正值會增加指定的執行個體數量的容量，負值則會減少指定的執行個體數量的容量。**  

```
Write-ASScalingPolicy -AutoScalingGroupName my-asg -AdjustmentType "ChangeInCapacity" -PolicyName "myScaleInPolicy" -ScalingAdjustment -1
```
**輸出：**  

```
arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef:autoScalingGroupName/my-asg
:policyName/myScaleInPolicy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-ASScheduledUpdateGroupAction`
<a name="auto-scaling_PutScheduledUpdateGroupAction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-ASScheduledUpdateGroupAction`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立或更新一次性排程動作，以在指定的開始時間變更所需的容量。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS Budgets 使用 Tools for PowerShell V5 的範例
<a name="powershell_budgets_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS Budgets。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `New-BGTBudget`
<a name="budgets_CreateBudget_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-BGTBudget`。

**Tools for PowerShell V5**  
**範例 1：透過電子郵件通知，建立具有指定預算和時間限制的新預算。**  

```
$notification = @{
    NotificationType = "ACTUAL"
    ComparisonOperator = "GREATER_THAN"
    Threshold = 80
}

$addressObject = @{
    Address = @("user@domain.com")
    SubscriptionType = "EMAIL"
}

$subscriber = New-Object Amazon.Budgets.Model.NotificationWithSubscribers
$subscriber.Notification = $notification
$subscriber.Subscribers.Add($addressObject)

$startDate = [datetime]::new(2017,09,25)
$endDate = [datetime]::new(2017,10,25)

New-BGTBudget -Budget_BudgetName "Tester" -Budget_BudgetType COST -CostTypes_IncludeTax $true -Budget_TimeUnit MONTHLY -BudgetLimit_Unit USD -TimePeriod_Start $startDate -TimePeriod_End $endDate -AccountId 123456789012 -BudgetLimit_Amount 200 -NotificationsWithSubscriber $subscriber
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateBudget](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS Cloud9 使用 Tools for PowerShell V5 的範例
<a name="powershell_cloud9_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS Cloud9。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-C9EnvironmentData`
<a name="cloud9_DescribeEnvironments_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-C9EnvironmentData`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定 AWS Cloud9 開發環境的相關資訊。**  

```
Get-C9EnvironmentData -EnvironmentId 685f892f431b45c2b28cb69eadcdb0EX,1980b80e5f584920801c09086667f0EX
```
**輸出：**  

```
Arn         : arn:aws:cloud9:us-east-1:123456789012:environment:685f892f431b45c2b28cb69eadcdb0EX
Description : Created from CodeStar.
Id          : 685f892f431b45c2b28cb69eadcdb0EX
Lifecycle   : Amazon.Cloud9.Model.EnvironmentLifecycle
Name        : my-demo-ec2-env
OwnerArn    : arn:aws:iam::123456789012:user/MyDemoUser
Type        : ec2

Arn         : arn:aws:cloud9:us-east-1:123456789012:environment:1980b80e5f584920801c09086667f0EX
Description :
Id          : 1980b80e5f584920801c09086667f0EX
Lifecycle   : Amazon.Cloud9.Model.EnvironmentLifecycle
Name        : my-demo-ssh-env
OwnerArn    : arn:aws:iam::123456789012:user/MyDemoUser
Type        : ssh
```
**範例 2：此範例會取得指定 AWS Cloud9 開發環境生命週期狀態的相關資訊。**  

```
(Get-C9EnvironmentData -EnvironmentId 685f892f431b45c2b28cb69eadcdb0EX).Lifecycle
```
**輸出：**  

```
FailureResource Reason Status
--------------- ------ ------
                       CREATED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEnvironments](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-C9EnvironmentList`
<a name="cloud9_ListEnvironments_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-C9EnvironmentList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得 available AWS Cloud9 開發環境識別符的清單。**  

```
Get-C9EnvironmentList
```
**輸出：**  

```
685f892f431b45c2b28cb69eadcdb0EX
1980b80e5f584920801c09086667f0EX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListEnvironments](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-C9EnvironmentMembershipList`
<a name="cloud9_DescribeEnvironmentMemberships_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-C9EnvironmentMembershipList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定 AWS Cloud9 開發環境的環境成員相關資訊。**  

```
Get-C9EnvironmentMembershipList -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
**輸出：**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-write
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX

EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
**範例 2：此範例取得有關指定 AWS Cloud9 開發環境擁有者的資訊。**  

```
Get-C9EnvironmentMembershipList -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission owner
```
**輸出：**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
**範例 3：此範例取得多個 AWS Cloud9 開發環境之指定環境成員的相關資訊。**  

```
Get-C9EnvironmentMembershipList -UserArn arn:aws:iam::123456789012:user/MyDemoUser
```
**輸出：**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/17/2018 7:48:14 PM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX

EnvironmentId : 1980b80e5f584920801c09086667f0EX
LastAccess    : 1/16/2018 11:21:24 PM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEnvironmentMemberships](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-C9EnvironmentStatus`
<a name="cloud9_DescribeEnvironmentStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-C9EnvironmentStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定 AWS Cloud9 開發環境的狀態資訊。**  

```
Get-C9EnvironmentStatus -EnvironmentId 349c86d4579e4e7298d500ff57a6b2EX
```
**輸出：**  

```
Message                     Status
-------                     ------
Environment is ready to use ready
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEnvironmentStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-C9EnvironmentEC2`
<a name="cloud9_CreateEnvironmentEc2_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-C9EnvironmentEC2`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定的設定建立 an AWS Cloud9 開發環境、啟動 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體，然後從執行個體連線至環境。**  

```
New-C9EnvironmentEC2 -Name my-demo-env -AutomaticStopTimeMinutes 60 -Description "My demonstration development environment." -InstanceType t2.micro -OwnerArn arn:aws:iam::123456789012:user/MyDemoUser -SubnetId subnet-d43a46EX
```
**輸出：**  

```
ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateEnvironmentEc2](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-C9EnvironmentMembership`
<a name="cloud9_CreateEnvironmentMembership_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-C9EnvironmentMembership`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的環境成員新增至指定的 AWS Cloud9 開發環境。**  

```
New-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission read-write
```
**輸出：**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-write
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-C9Environment`
<a name="cloud9_DeleteEnvironment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-C9Environment`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的 AWS Cloud9 開發環境。如果 Amazon EC2 執行個體連線至環境，該執行個體也會終止。**  

```
Remove-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteEnvironment](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-C9EnvironmentMembership`
<a name="cloud9_DeleteEnvironmentMembership_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-C9EnvironmentMembership`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的 AWS Cloud9 開發環境刪除指定的環境成員。**  

```
Remove-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-C9Environment`
<a name="cloud9_UpdateEnvironment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-C9Environment`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更指定之 existing AWS Cloud9 開發環境的指定設定。**  

```
Update-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Description "My changed demonstration development environment." -Name my-changed-demo-env
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateEnvironment](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-C9EnvironmentMembership`
<a name="cloud9_UpdateEnvironmentMembership_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-C9EnvironmentMembership`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更指定 AWS Cloud9 開發環境之指定現有環境成員的設定。**  

```
Update-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission read-only
```
**輸出：**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-only
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)。

# CloudFormation 使用 Tools for PowerShell V5 的範例
<a name="powershell_cloudformation_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 CloudFormation。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-CFNStack`
<a name="cloudformation_DescribeStacks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFNStack`。

**Tools for PowerShell V5**  
**範例 1：傳回描述所有使用者堆疊的堆疊執行個體集合。**  

```
Get-CFNStack
```
**範例 2：傳回描述指定堆疊的堆疊執行個體**  

```
Get-CFNStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFNStackEvent`
<a name="cloudformation_DescribeStackEvents_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFNStackEvent`。

**Tools for PowerShell V5**  
**範例 1：傳回特定堆疊的所有堆疊相關事件。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStackEvents](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFNStackResource`
<a name="cloudformation_DescribeStackResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFNStackResource`。

**Tools for PowerShell V5**  
**範例 1：傳回透過邏輯 ID "MyDBInstance" 在與指定堆疊相關聯的範本中識別的資源描述。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStackResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFNStackResourceList`
<a name="cloudformation_DescribeStackResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFNStackResourceList`。

**Tools for PowerShell V5**  
**範例 1：傳回最多 100 個與指定堆疊相關聯的資源 AWS 描述。若要取得與堆疊相關聯的所有資源詳細資訊，請使用 Get-CFNStackResourceSummary，這也支援手動分頁結果。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**範例 2：傳回邏輯 ID "Ec2Instance" 在與指定堆疊相關聯的範本中識別的 Amazon EC2 執行個體描述。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**範例 3：傳回最多 100 個與堆疊相關聯的資源描述，其中包含由執行個體 ID "i-123456" 識別的 Amazon EC2 執行個體。若要取得與堆疊相關聯的所有資源詳細資訊，請使用 Get-CFNStackResourceSummary，這也支援手動分頁結果。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456"
```
**範例 4：傳回堆疊範本中邏輯 ID "Ec2Instance" 所識別的 Amazon EC2 執行個體描述。堆疊是使用其包含的資源的實體資源 ID 來識別，在此情況下，也會使用執行個體 ID 為 "i-123456" 的 Amazon EC2 執行個體。根據範本內容，也可以使用不同的實體資源來識別堆疊，例如 Amazon S3 儲存貯體。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456" -LogicalResourceId "Ec2Instance"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStackResources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFNStackResourceSummary`
<a name="cloudformation_ListStackResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFNStackResourceSummary`。

**Tools for PowerShell V5**  
**範例 1：傳回與指定堆疊相關聯的所有資源的描述。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListStackResources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFNStackSummary`
<a name="cloudformation_ListStacks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFNStackSummary`。

**Tools for PowerShell V5**  
**範例 1：傳回所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary
```
**範例 2：傳回目前正在建立之所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary -StackStatusFilter "CREATE_IN_PROGRESS"
```
**範例 3：傳回目前正在建立或更新之所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary -StackStatusFilter @("CREATE_IN_PROGRESS", "UPDATE_IN_PROGRESS")
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListStacks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFNTemplate`
<a name="cloudformation_GetTemplate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFNTemplate`。

**Tools for PowerShell V5**  
**範例 1：傳回與指定堆疊相關聯的範本。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetTemplate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Measure-CFNTemplateCost`
<a name="cloudformation_EstimateTemplateCost_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Measure-CFNTemplateCost`。

**Tools for PowerShell V5**  
**範例 1：傳回 AWS 簡易每月計算器 URL，其中包含查詢字串，描述執行範本所需的資源。範本是從指定的 Amazon S3 URL 和套用的單一自訂參數取得。參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Measure-CFNTemplateCost -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                        -Region us-west-1 `
                        -Parameter @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" }
```
**範例 2：傳回 AWS 簡易每月計算器 URL，其中包含查詢字串，描述執行範本所需的資源。範本會從提供的內容剖析，並套用自訂參數 (此範例假設範本內容已宣告兩個參數：'KeyName' 和 'InstanceType')。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**範例 3：使用 New-Object 建置一組範本參數，並傳回具有查詢字串的 AWS 簡易每月計算器 URL，該字串說明執行範本所需的資源。範本是從提供的內容中剖析，具有自訂參數 (此範例假設範本內容已宣告兩個參數：'KeyName' 和 'InstanceType')。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "KeyName"
$p1.ParameterValue = "myKeyPairName"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "InstanceType"
$p2.ParameterValue = "m1.large"

Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" -Parameter @( $p1, $p2 )
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CFNStack`
<a name="cloudformation_CreateStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CFNStack`。

**Tools for PowerShell V5**  
**範例 1：使用指定的名稱建立新堆疊。範本是根據提供的內容和自訂參數 ('PK1' 和 'PK2' 代表範本內容中宣告的參數名稱，'PV1' 和 'PV2' 代表這些參數的值) 進行剖析。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果堆疊建立失敗，則不會還原。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" }) `
             -DisableRollback $true
```
**範例 2：使用指定的名稱建立新堆疊。範本是根據提供的內容和自訂參數 ('PK1' 和 'PK2' 代表範本內容中宣告的參數名稱，'PV1' 和 'PV2' 代表這些參數的值) 進行剖析。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果堆疊建立失敗，則會還原。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "PK1"
$p1.ParameterValue = "PV1"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "PK2"
$p2.ParameterValue = "PV2"

New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( $p1, $p2 ) `
             -OnFailure "ROLLBACK"
```
**範例 3：使用指定的名稱建立新堆疊。範本是從具有自訂參數 ('PK1' 代表範本內容中宣告的參數名稱，'PV1' 代表參數的值) 的 Amazon S3 URL 取得。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果建立堆疊失敗，則會還原 (與指定 -DisableRollback \$1false 相同)。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 4：使用指定的名稱建立新堆疊。範本是從具有自訂參數 ('PK1' 代表範本內容中宣告的參數名稱，'PV1' 代表參數的值) 的 Amazon S3 URL 取得。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果建立堆疊失敗，則會還原 (與指定 -DisableRollback \$1false 相同)。指定的通知 AEN 會收到已發佈的堆疊相關事件。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" } `
             -NotificationARN @( "arn1", "arn2" )
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CFNStack`
<a name="cloudformation_DeleteStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CFNStack`。

**Tools for PowerShell V5**  
**範例 1：刪除指定的堆疊。**  

```
Remove-CFNStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Resume-CFNUpdateRollback`
<a name="cloudformation_ContinueUpdateRollback_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Resume-CFNUpdateRollback`。

**Tools for PowerShell V5**  
**範例 1：繼續還原具名堆疊，其應處於 'UPDATE\$1ROLLBACK\$1FAILED' 狀態。如果繼續還原成功，堆疊將進入狀態 'UPDATE\$1ROLLBACK\$1COMPLETE'。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-CFNUpdateStack`
<a name="cloudformation_CancelUpdateStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-CFNUpdateStack`。

**Tools for PowerShell V5**  
**範例 1：取消指定堆疊的更新。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelUpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Test-CFNStack`
<a name="cloudformation_Test-CFNStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Test-CFNStack`。

**Tools for PowerShell V5**  
**範例 1：測試堆疊是否已達到 UPDATE\$1ROLLBACK\$1COMPLETE、CREATE\$1COMPLETE、ROLLBACK\$1COMPLETE 或 UPDATE\$1COMPLETE 狀態之一。**  

```
Test-CFNStack -StackName MyStack
```
**輸出：**  

```
False
```
**範例 2：測試堆疊是否已達到 UPDATE\$1COMPLETE 或 UPDATE\$1ROLLBACK\$1COMPLETE 狀態。**  

```
Test-CFNStack -StackName MyStack -Status UPDATE_COMPLETE,UPDATE_ROLLBACK_COMPLETE
```
**輸出：**  

```
True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Test-CFNStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Test-CFNTemplate`
<a name="cloudformation_ValidateTemplate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Test-CFNTemplate`。

**Tools for PowerShell V5**  
**範例 1：驗證指定的範本內容。輸出中詳細說明範本的功能、描述和參數。**  

```
Test-CFNTemplate -TemplateBody "{TEMPLATE CONTENT HERE}"
```
**範例 2：驗證透過 Amazon S3 URL 存取的指定範本。輸出中詳細說明範本的功能、描述和參數。**  

```
Test-CFNTemplate -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ValidateTemplate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CFNStack`
<a name="cloudformation_UpdateStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CFNStack`。

**Tools for PowerShell V5**  
**範例 1：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 代表範本中宣告的參數名稱，而 'PV1' 代表其值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 2：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**範例 3：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 代表範本中宣告的參數名稱，而 'PV2' 代表其值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 4：使用從 Amazon S3 取得的指定範本和自訂參數來更新堆疊 'myStack'。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**範例 5：更新堆疊 'myStack'，在本範例中假設包含 IAM 資源，具有從 Amazon S3 取得的指定範本和自訂參數。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。包含 IAM 資源的堆疊需要指定 -Capabilities "CAPABILITY\$1IAM" 參數，否則更新會失敗，並顯示 'InsufficientCapabilities' 錯誤。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } ) `
                -Capabilities "CAPABILITY_IAM"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Wait-CFNStack`
<a name="cloudformation_Wait-CFNStack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Wait-CFNStack`。

**Tools for PowerShell V5**  
**範例 1：測試堆疊是否已達到 UPDATE\$1ROLLBACK\$1COMPLETE、CREATE\$1COMPLETE、ROLLBACK\$1COMPLETE 或 UPDATE\$1COMPLETE 狀態之一。如果堆疊不在其中一個狀態，命令會先休眠兩秒鐘，然後再測試狀態。這動作會一直重複，直到堆疊達到其中一個請求狀態，或經過 60 秒的預設逾時期間為止。如果超過逾時期間，則會擲回例外狀況。如果堆疊在逾時期間達到其中一個請求的狀態，則會傳回管道。**  

```
$stack = Wait-CFNStack -StackName MyStack
```
**範例 2：此範例會等待總共 5 分鐘 (300 秒)，讓堆疊達到其中一個指定的狀態。在此範例中，逾時之前達到了該狀態，因此堆疊物件會傳回管道。**  

```
Wait-CFNStack -StackName MyStack -Timeout 300 -Status CREATE_COMPLETE,ROLLBACK_COMPLETE
```
**輸出：**  

```
Capabilities      : {CAPABILITY_IAM}
ChangeSetId       :
CreationTime      : 6/1/2017 9:29:33 AM
Description       : AWS CloudFormation Sample Template ec2_instance_with_instance_profile: Create an EC2 instance with an associated instance profile. **WARNING** This template creates one or more Amazon EC2
                    instances and an Amazon SQS queue. You will be billed for the AWS resources used if you create a stack from this template.
DisableRollback   : False
LastUpdatedTime   : 1/1/0001 12:00:00 AM
NotificationARNs  : {}
Outputs           : {}
Parameters        : {}
RoleARN           :
StackId           : arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/7ea87b50-46e7-11e7-9c9b-503a90a9c4d1
StackName         : MyStack
StackStatus       : CREATE_COMPLETE
StackStatusReason :
Tags              : {}
TimeoutInMinutes  : 0
```
**範例 3：此範例示範堆疊在逾時期間 (在此情況下預設為 60 秒) 內未達到其中一個請求狀態時的錯誤輸出。**  

```
Wait-CFNStack -StackName MyStack -Status CREATE_COMPLETE,ROLLBACK_COMPLETE
```
**輸出：**  

```
Wait-CFNStack : Timed out after 60 seconds waiting for CloudFormation stack MyStack in region us-west-2 to reach one of state(s): UPDATE_ROLLBACK_COMPLETE,CREATE_COMPLETE,ROLLBACK_COMPLETE,UPDATE_COMPLETE
At line:1 char:1
+ Wait-CFNStack -StackName MyStack -State CREATE_COMPLETE,ROLLBACK_COMPLETE
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Amazon.PowerShe...tCFNStackCmdlet:WaitCFNStackCmdlet) [Wait-CFNStack], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Amazon.PowerShell.Cmdlets.CFN.WaitCFNStackCmdlet
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Wait-CFNStack](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 CloudFront 範例
<a name="powershell_cloudfront_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 CloudFront 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-CFCloudFrontOriginAccessIdentity`
<a name="cloudfront_GetCloudFrontOriginAccessIdentity_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFCloudFrontOriginAccessIdentity`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回由 -Id 參數指定的特定 Amazon CloudFront 原始存取身分。雖然不需要 -Id 參數，但如果沒有指定該參數，就不會傳回任何結果。**  

```
Get-CFCloudFrontOriginAccessIdentity -Id E3XXXXXXXXXXRT
```
**輸出：**  

```
      CloudFrontOriginAccessIdentityConfig    Id                                      S3CanonicalUserId
      ------------------------------------    --                                      -----------------
      Amazon.CloudFront.Model.CloudFrontOr... E3XXXXXXXXXXRT                          4b6e...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetCloudFrontOriginAccessIdentity](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFCloudFrontOriginAccessIdentityConfig`
<a name="cloudfront_GetCloudFrontOriginAccessIdentityConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFCloudFrontOriginAccessIdentityConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回 -Id 參數所指定之單一 Amazon CloudFront 原始存取身分的組態資訊。如果未指定 -Id 參數，則會發生錯誤。**  

```
Get-CFCloudFrontOriginAccessIdentityConfig -Id E3XXXXXXXXXXRT
```
**輸出：**  

```
      CallerReference                                             Comment
      ---------------                                             -------
      mycallerreference: 2/1/2011 1:16:32 PM                      Caller reference: 2/1/2011 1:16:32 PM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetCloudFrontOriginAccessIdentityConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFCloudFrontOriginAccessIdentityList`
<a name="cloudfront_ListCloudFrontOriginAccessIdentities_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFCloudFrontOriginAccessIdentityList`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回 Amazon CloudFront 原始存取身分的清單。由於 -MaxItem 參數指定值 2，因此結果包含兩個身分。**  

```
Get-CFCloudFrontOriginAccessIdentityList -MaxItem 2
```
**輸出：**  

```
IsTruncated : True
Items       : {E326XXXXXXXXXT, E1YWXXXXXXX9B}
Marker      :
MaxItems    : 2
NextMarker  : E1YXXXXXXXXX9B
Quantity    : 2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFDistribution`
<a name="cloudfront_GetDistribution_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFDistribution`。

**Tools for PowerShell V5**  
**範例 1：擷取特定分佈的資訊。**  

```
Get-CFDistribution -Id EXAMPLE0000ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDistribution](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFDistributionConfig`
<a name="cloudfront_GetDistributionConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFDistributionConfig`。

**Tools for PowerShell V5**  
**範例 1：擷取特定分佈的組態。**  

```
Get-CFDistributionConfig -Id EXAMPLE0000ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDistributionConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFDistributionList`
<a name="cloudfront_ListDistributions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFDistributionList`。

**Tools for PowerShell V5**  
**範例 1：傳回分佈。**  

```
Get-CFDistributionList
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDistributions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CFDistribution`
<a name="cloudfront_CreateDistribution_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CFDistribution`。

**Tools for PowerShell V5**  
**範例 1：建立以日誌記錄和快取設定的基本 CloudFront 分佈。**  

```
$origin = New-Object Amazon.CloudFront.Model.Origin
$origin.DomainName = "amzn-s3-demo-bucket.s3.amazonaws.com"
$origin.Id = "UniqueOrigin1"
$origin.S3OriginConfig = New-Object Amazon.CloudFront.Model.S3OriginConfig
$origin.S3OriginConfig.OriginAccessIdentity = ""
New-CFDistribution `
      -DistributionConfig_Enabled $true `
      -DistributionConfig_Comment "Test distribution" `
      -Origins_Item $origin `
      -Origins_Quantity 1 `
      -Logging_Enabled $true `
      -Logging_IncludeCookie $true `
      -Logging_Bucket amzn-s3-demo-logging-bucket.s3.amazonaws.com `
      -Logging_Prefix "help/" `
      -DistributionConfig_CallerReference Client1 `
      -DistributionConfig_DefaultRootObject index.html `
      -DefaultCacheBehavior_TargetOriginId $origin.Id `
      -ForwardedValues_QueryString $true `
      -Cookies_Forward all `
      -WhitelistedNames_Quantity 0 `
      -TrustedSigners_Enabled $false `
      -TrustedSigners_Quantity 0 `
      -DefaultCacheBehavior_ViewerProtocolPolicy allow-all `
      -DefaultCacheBehavior_MinTTL 1000 `
      -DistributionConfig_PriceClass "PriceClass_All" `
      -CacheBehaviors_Quantity 0 `
      -Aliases_Quantity 0
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDistribution](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CFInvalidation`
<a name="cloudfront_CreateInvalidation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CFInvalidation`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 ID 為 EXAMPLENSTXAXE 的分佈上建立新的失效證明。CallerReference 是使用者選擇的唯一 ID；在此情況下，會使用代表 2019 年 5 月 15 日上午 9:00 的時間戳記。\$1Paths 變數存放了使用者不想要當作分佈快取一部分的映像和媒體檔案的三個路徑。-Paths\$1Quantity 參數值是 -Paths\$1Item 參數中指定的路徑總數。**  

```
$Paths = "/images/*.gif", "/images/image1.jpg", "/videos/*.mp4"
New-CFInvalidation -DistributionId "EXAMPLENSTXAXE" -InvalidationBatch_CallerReference 20190515090000 -Paths_Item $Paths -Paths_Quantity 3
```
**輸出：**  

```
Invalidation                         Location                                                                                          
------------                         --------                                                                                          
Amazon.CloudFront.Model.Invalidation https://cloudfront.amazonaws.com/2018-11-05/distribution/EXAMPLENSTXAXE/invalidation/EXAMPLE8NOK9H
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateInvalidation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CFSignedCookie`
<a name="cloudfront_New-CFSignedCookie_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CFSignedCookie`。

**Tools for PowerShell V5**  
**範例 1：使用標準政策為指定的資源建立已簽署的 Cookie。Cookie 有效期為一年。**  

```
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/image1.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddYears(1)
}
New-CFSignedCookie @params
```
**輸出：**  

```
Expires
-------
[CloudFront-Expires, 1472227284]
```
**範例 2：使用自訂政策為指定的資源建立已簽署的 Cookie。Cookie 將在 24 小時內生效，並在一週後到期。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/content/*.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=$start.AddDays(7)
    "ActiveFrom"=$start
}

New-CFSignedCookie @params
```
**輸出：**  

```
Policy
------
[CloudFront-Policy, eyJTd...wIjo...
```
**範例 3：使用自訂政策為指定的資源建立已簽署的 Cookie。Cookie 將在 24 小時內生效，並在一週後到期。資源的存取僅限於指定的 ip 範圍。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/content/*.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=$start.AddDays(7)
    "ActiveFrom"=$start
	"IpRange"="192.0.2.0/24"
}

New-CFSignedCookie @params
```
**輸出：**  

```
Policy                                                                                                                                         ------                                                                                                                                         [CloudFront-Policy, eyJTd...wIjo...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [New-CFSignedCookie](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CFSignedUrl`
<a name="cloudfront_New-CFSignedUrl_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CFSignedUrl`。

**Tools for PowerShell V5**  
**範例 1：使用標準政策建立指定資源的已簽署 URL。URL 的有效期為一小時。包含已簽署 URL 的 System.Uri 物件會發送到管道。**  

```
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddHours(1)
}
New-CFSignedUrl @params
```
**範例 2：使用自訂政策建立指定資源的已簽署 URL。url 將在 24 小時內生效，並在一週後到期。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddDays(7)
    "ActiveFrom"=$start
}
New-CFSignedUrl @params
```
**範例 3：使用自訂政策建立指定資源的已簽署 URL。url 將在 24 小時內生效，並在一週後到期。資源的存取僅限於指定的 ip 範圍。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddDays(7)
    "ActiveFrom"=$start
    "IpRange"="192.0.2.0/24"	
}
New-CFSignedUrl @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [New-CFSignedUrl](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 CloudTrail 範例
<a name="powershell_cloudtrail_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 CloudTrail 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Find-CTEvent`
<a name="cloudtrail_LookupEvents_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Find-CTEvent`。

**Tools for PowerShell V5**  
**範例 1：傳回過去七天內發生的所有事件。根據預設，Cmdlet 會自動進行多次呼叫以傳遞所有事件，並在服務指出沒有其他資料可用時結束。**  

```
Find-CTEvent
```
**範例 2：傳回過去七天內發生的所有事件，指定不是目前 shell 預設值的區域。**  

```
Find-CTEvent -Region eu-central-1
```
**範例 3：傳回與 RunInstances API 呼叫相關聯的所有事件。**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**範例 4：傳回前 5 個可用的事件。**  

```
Find-CTEvent -MaxResult 5
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [LookupEvents](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CTTrail`
<a name="cloudtrail_DescribeTrails_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CTTrail`。

**Tools for PowerShell V5**  
**範例 1：傳回與您的帳戶目前區域相關聯的所有追蹤設定。**  

```
Get-CTTrail
```
**範例 2：傳回指定的追蹤設定。**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**範例 3：傳回在目前 shell 預設 (在本案例中為法蘭克福 (eu-central-1) 區域) 以外區域中建立的指定追蹤設定。**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTrails](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CTTrailStatus`
<a name="cloudtrail_GetTrailStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CTTrailStatus`。

**Tools for PowerShell V5**  
**範例 1：傳回名為 'myExampleTrail' 的追蹤狀態資訊。傳回的資料包含交付錯誤、Amazon SNS 和 Amazon S3 錯誤，以及開始和停止追蹤記錄時間的相關資訊。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**範例 2：傳回在目前 shell 預設值 (在本案例中為法蘭克福 (eu-central-1) 區域) 以外區域中建立的追蹤狀態資訊。**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetTrailStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CTTrail`
<a name="cloudtrail_CreateTrail_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CTTrail`。

**Tools for PowerShell V5**  
**範例 1：建立使用儲存貯體 'amzn-s3-demo-bucket' 進行日誌檔儲存的追蹤記錄。**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**範例 2：建立使用儲存貯體 'amzn-s3-demo-bucket' 進行日誌檔儲存的追蹤記錄。代表日誌的 S3 物件具有 'mylogs' 的常用鍵字首。當新日誌交付至儲存貯體時，傳送通知至 SNS 主題 'mlog-deliverytopic'。此範例使用 splatting 將參數值提供給 Cmdlet。**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateTrail](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CTTrail`
<a name="cloudtrail_DeleteTrail_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CTTrail`。

**Tools for PowerShell V5**  
**範例 1：刪除指定的追蹤記錄。執行命令之前，系統會提示您確認。若要隱藏確認，請新增 -Force 切換變數。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteTrail](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-CTLogging`
<a name="cloudtrail_StartLogging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-CTLogging`。

**Tools for PowerShell V5**  
**範例 1：開始記錄名為 'myExampleTrail' 之線索的 AWS API 呼叫和日誌檔案交付。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Start-CTLogging -Name myExampleTrail
```
**範例 2：開始記錄在目前 shell 預設 （在此情況下為法蘭克福 (eu-central-1) 區域） 以外區域中建立之線索的 AWS API 呼叫和日誌檔案交付。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartLogging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-CTLogging`
<a name="cloudtrail_StopLogging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-CTLogging`。

**Tools for PowerShell V5**  
**範例 1：暫停記錄名為 'myExampleTrail' 之線索的 AWS API 呼叫和日誌檔案交付。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Stop-CTLogging -Name myExampleTrail
```
**範例 2：暫停記錄在目前 shell 預設 （在此情況下為法蘭克福 (eu-central-1) 區域） 以外區域中建立之線索的 AWS API 呼叫和日誌檔案交付。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopLogging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CTTrail`
<a name="cloudtrail_UpdateTrail_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CTTrail`。

**Tools for PowerShell V5**  
**範例 1：更新指定的追蹤，以便記錄全域服務事件 (例如來自 IAM 的事件)，並將後續日誌檔的常見金鑰字首變更為 'globallogs'。**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**範例 2：更新指定的追蹤，以便將新日誌交付的通知傳送至指定的 SNS 主題。**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**範例 3：更新指定的追蹤，以便將日誌傳送到不同的儲存貯體。**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateTrail](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 CloudWatch 範例
<a name="powershell_cloudwatch_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 CloudWatch 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-CWDashboard`
<a name="cloudwatch_GetDashboard_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CWDashboard`。

**Tools for PowerShell V5**  
**範例 1：傳回指定儀表板內文的 arn。**  

```
Get-CWDashboard -DashboardName Dashboard1
```
**輸出：**  

```
DashboardArn                                          DashboardBody
------------                                          -------------
arn:aws:cloudwatch::123456789012:dashboard/Dashboard1 {...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDashboard](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CWDashboardList`
<a name="cloudwatch_ListDashboards_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CWDashboardList`。

**Tools for PowerShell V5**  
**範例 1：傳回您帳戶的儀表板集合。**  

```
Get-CWDashboardList
```
**輸出：**  

```
DashboardArn DashboardName LastModified        Size
------------ ------------- ------------        ----
arn:...      Dashboard1    7/6/2017 8:14:15 PM 252
```
**範例 2：傳回名稱以 'dev' 開頭之帳戶的儀表板集合。**  

```
Get-CWDashboardList -DashboardNamePrefix dev
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDashboards](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CWDashboard`
<a name="cloudwatch_DeleteDashboards_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CWDashboard`。

**Tools for PowerShell V5**  
**範例 1：刪除指定儀表板，並在執行前要求確認。若要略過確認，請將 -Force 切換變數新增至命令。**  

```
Remove-CWDashboard -DashboardName Dashboard1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteDashboards](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-CWDashboard`
<a name="cloudwatch_PutDashboard_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-CWDashboard`。

**Tools for PowerShell V5**  
**範例 1：建立或更新名為 'Dashboard1' 的儀表板，以並列包含兩個指標小工具。**  

```
$dashBody = @"
{
    "widgets":[
        {
             "type":"metric",
             "x":0,
             "y":0,
             "width":12,
             "height":6,
             "properties":{
                "metrics":[
                   [
                      "AWS/EC2",
                      "CPUUtilization",
                      "InstanceId",
                      "i-012345"
                   ]
                ],
                "period":300,
                "stat":"Average",
                "region":"us-east-1",
                "title":"EC2 Instance CPU"
             }
        },
        {
             "type":"metric",
             "x":12,
             "y":0,
             "width":12,
             "height":6,
             "properties":{
                "metrics":[
                   [
                      "AWS/S3",
                      "BucketSizeBytes",
                      "BucketName",
                      "amzn-s3-demo-bucket"
                   ]
                ],
                "period":86400,
                "stat":"Maximum",
                "region":"us-east-1",
                "title":"amzn-s3-demo-bucket bytes"
            }
        }
    ]
}
"@

Write-CWDashboard -DashboardName Dashboard1 -DashboardBody $dashBody
```
**範例 2：建立或更新儀表板，將描述儀表板的內容導入 cmdlet。**  

```
$dashBody = @"
{
...
}
"@
        
$dashBody | Write-CWDashboard -DashboardName Dashboard1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutDashboard](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-CWMetricData`
<a name="cloudwatch_PutMetricData_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-CWMetricData`。

**Tools for PowerShell V5**  
**範例 1：建立新的 MetricDatum 物件，並將其寫入 Amazon Web Services CloudWatch 指標。**  

```
### Create a MetricDatum .NET object
$Metric = New-Object -TypeName Amazon.CloudWatch.Model.MetricDatum
$Metric.Timestamp = [DateTime]::UtcNow
$Metric.MetricName = 'CPU'
$Metric.Value = 50

### Write the metric data to the CloudWatch service
Write-CWMetricData -Namespace instance1 -MetricData $Metric
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutMetricData](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 CodeCommit 範例
<a name="powershell_codecommit_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 CodeCommit 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-CCBranch`
<a name="codecommit_GetBranch_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CCBranch`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定儲存庫之指定分支的相關資訊。**  

```
Get-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch
```
**輸出：**  

```
BranchName                              CommitId
----------                              --------
MyNewBranch                             7763222d...561fc9c9
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBranch](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CCBranchList`
<a name="codecommit_ListBranches_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CCBranchList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定儲存庫的分支名稱清單。**  

```
Get-CCBranchList -RepositoryName MyDemoRepo
```
**輸出：**  

```
master
MyNewBranch
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListBranches](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CCRepository`
<a name="codecommit_GetRepository_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CCRepository`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定儲存庫的資訊。**  

```
Get-CCRepository -RepositoryName MyDemoRepo
```
**輸出：**  

```
AccountId             : 80398EXAMPLE
Arn                   : arn:aws:codecommit:us-east-1:80398EXAMPLE:MyDemoRepo
CloneUrlHttp          : https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CloneUrlSsh           : ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CreationDate          : 9/8/2015 3:21:33 PM
DefaultBranch         :
LastModifiedDate      : 9/8/2015 3:21:33 PM
RepositoryDescription : This is a repository for demonstration purposes.
RepositoryId          : c7d0d2b0-ce40-4303-b4c3-38529EXAMPLE
RepositoryName        : MyDemoRepo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetRepository](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CCRepositoryBatch`
<a name="codecommit_BatchGetRepositories_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CCRepositoryBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例確認哪些指定的儲存庫可找到和找不到。**  

```
Get-CCRepositoryBatch -RepositoryName MyDemoRepo, MyNewRepo, AMissingRepo
```
**輸出：**  

```
Repositories                            RepositoriesNotFound
------------                            --------------------
{MyDemoRepo, MyNewRepo}                {AMissingRepo}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchGetRepositories](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CCRepositoryList`
<a name="codecommit_ListRepositories_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CCRepositoryList`。

**Tools for PowerShell V5**  
**範例 1：此範例依儲存庫名稱，以遞增順序列出所有儲存庫。**  

```
Get-CCRepositoryList -Order Ascending -SortBy RepositoryName
```
**輸出：**  

```
RepositoryId                            RepositoryName
------------                            --------------
c7d0d2b0-ce40-4303-b4c3-38529EXAMPLE    MyDemoRepo
05f30c66-e3e3-4f91-a0cd-1c84aEXAMPLE    MyNewRepo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListRepositories](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CCBranch`
<a name="codecommit_CreateBranch_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CCBranch`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立具有指定儲存庫之指定名稱，以及指定遞交 ID 的新分支。**  

```
New-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch -CommitId 7763222d...561fc9c9
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateBranch](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CCRepository`
<a name="codecommit_CreateRepository_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CCRepository`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立具有指定名稱和指定描述的新儲存庫。**  

```
New-CCRepository -RepositoryName MyDemoRepo -RepositoryDescription "This is a repository for demonstration purposes."
```
**輸出：**  

```
AccountId             : 80398EXAMPLE
Arn                   : arn:aws:codecommit:us-east-1:80398EXAMPLE:MyDemoRepo
CloneUrlHttp          : https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CloneUrlSsh           : ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CreationDate          : 9/18/2015 4:13:25 PM
DefaultBranch         :
LastModifiedDate      : 9/18/2015 4:13:25 PM
RepositoryDescription : This is a repository for demonstration purposes.
RepositoryId          : 43ef2443-3372-4b12-9e78-65c27EXAMPLE
RepositoryName        : MyDemoRepo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateRepository](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CCRepository`
<a name="codecommit_DeleteRepository_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CCRepository`。

**Tools for PowerShell V5**  
**範例 1：此範例強制刪除指定的儲存庫。繼續之前，此命令會先提示確認。新增 -Force 切換變數可刪除儲存庫，無需提示。**  

```
Remove-CCRepository -RepositoryName MyDemoRepo
```
**輸出：**  

```
43ef2443-3372-4b12-9e78-65c27EXAMPLE
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DeleteRepository](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CCDefaultBranch`
<a name="codecommit_UpdateDefaultBranch_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CCDefaultBranch`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的儲存庫的預設分支變更為指定的分支。**  

```
Update-CCDefaultBranch -RepositoryName MyDemoRepo -DefaultBranchName MyNewBranch
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateDefaultBranch](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CCRepositoryDescription`
<a name="codecommit_UpdateRepositoryDescription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CCRepositoryDescription`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更指定之儲存庫的描述。**  

```
Update-CCRepositoryDescription -RepositoryName MyDemoRepo -RepositoryDescription "This is an updated description."
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateRepositoryDescription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CCRepositoryName`
<a name="codecommit_UpdateRepositoryName_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CCRepositoryName`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更指定之儲存庫的名稱。**  

```
Update-CCRepositoryName -NewName MyDemoRepo2 -OldName MyDemoRepo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateRepositoryName](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 CodeDeploy 範例
<a name="powershell_codedeploy_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 CodeDeploy 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-CDOnPremiseInstanceTag`
<a name="codedeploy_AddTagsToOnPremisesInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-CDOnPremiseInstanceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例為指定的內部部署執行個體新增具有指定鍵與值的內部部署執行個體標籤。**  

```
Add-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddTagsToOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDApplication`
<a name="codedeploy_GetApplication_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDApplication`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之應用程式的相關資訊。**  

```
Get-CDApplication -ApplicationName CodeDeployDemoApplication
```
**輸出：**  

```
ApplicationId                           ApplicationName              CreateTime              LinkedToGitHub
-------------                           ---------------              ----------              --------------
e07fb938-091e-4f2f-8963-4d3e8EXAMPLE    CodeDeployDemoApplication    7/20/2015 9:49:48 PM    False
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetApplication](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDApplicationBatch`
<a name="codedeploy_BatchGetApplications_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDApplicationBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之應用程式的相關資訊。**  

```
Get-CDApplicationBatch -ApplicationName CodeDeployDemoApplication, CodePipelineDemoApplication
```
**輸出：**  

```
ApplicationId                           ApplicationName              CreateTime              LinkedToGitHub
-------------                           ---------------              ----------              --------------
e07fb938-091e-4f2f-8963-4d3e8EXAMPLE    CodeDeployDemoApplication    7/20/2015 9:49:48 PM    False
1ecfd602-62f1-4038-8f0d-06688EXAMPLE    CodePipelineDemoApplication  8/13/2015 5:53:26 PM    False
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchGetApplications](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDApplicationList`
<a name="codedeploy_ListApplications_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDApplicationList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得可用應用程式的清單。**  

```
Get-CDApplicationList
```
**輸出：**  

```
CodeDeployDemoApplication
CodePipelineDemoApplication
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListApplications](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDApplicationRevision`
<a name="codedeploy_GetApplicationRevision_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDApplicationRevision`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之應用程式修訂版的相關資訊。**  

```
$revision = Get-CDApplicationRevision -ApplicationName CodeDeployDemoApplication -S3Location_Bucket amzn-s3-demo-bucket -Revision_RevisionType S3 -S3Location_Key 5xd27EX.zip -S3Location_BundleType zip -S3Location_ETag 4565c1ac97187f190c1a90265EXAMPLE
Write-Output ("Description = " + $revision.RevisionInfo.Description + ", RegisterTime = " + $revision.RevisionInfo.RegisterTime)
```
**輸出：**  

```
Description = Application revision registered by Deployment ID: d-CX9CHN3EX, RegisterTime = 07/20/2015 23:46:42
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetApplicationRevision](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDApplicationRevisionList`
<a name="codedeploy_ListApplicationRevisions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDApplicationRevisionList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之應用程式可用修訂的相關資訊。**  

```
ForEach ($revision in (Get-CDApplicationRevisionList -ApplicationName CodeDeployDemoApplication -Deployed Ignore)) {
>>   If ($revision.RevisionType -Eq "S3") {
>>     Write-Output ("Type = S3, Bucket = " + $revision.S3Location.Bucket + ", BundleType = " + $revision.S3Location.BundleType + ", ETag = " + $revision.S3Location.ETag + ", Key = " + $revision.S3Location.Key)
>>   }
>>   If ($revision.RevisionType -Eq "GitHub") {
>>     Write-Output ("Type = GitHub, CommitId = " + $revision.GitHubLocation.CommitId + ", Repository = " + $revision.GitHubLocation.Repository)
>>   }
>> }
>>
```
**輸出：**  

```
Type = S3, Bucket = amzn-s3-demo-bucket, BundleType = zip, ETag = 4565c1ac97187f190c1a90265EXAMPLE, Key = 5xd27EX.zip
Type = GitHub, CommitId = f48933c3...76405362, Repository = MyGitHubUser/CodeDeployDemoRepo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListApplicationRevisions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeployment`
<a name="codedeploy_GetDeployment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeployment`。

**Tools for PowerShell V5**  
**範例 1：此範例取得指定之部署的摘要資訊。**  

```
Get-CDDeployment -DeploymentId d-QZMRGSTEX
```
**輸出：**  

```
ApplicationName               : CodeDeployDemoApplication
CompleteTime                  : 7/23/2015 11:26:04 PM
CreateTime                    : 7/23/2015 11:24:43 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodeDeployDemoFleet
DeploymentId                  : d-QZMRGSTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded
```
**範例 2：此範例取得參與指定部署之執行個體狀態的相關資訊。**  

```
(Get-CDDeployment -DeploymentId d-QZMRGSTEX).DeploymentOverview
```
**輸出：**  

```
Failed     : 0
InProgress : 0
Pending    : 0
Skipped    : 0
Succeeded  : 3
```
**範例 3：此範例取得指定部署之應用程式修訂版的相關資訊。**  

```
(Get-CDDeployment -DeploymentId d-QZMRGSTEX).Revision.S3Location
```
**輸出：**  

```
Bucket     : amzn-s3-demo-bucket
BundleType : zip
ETag       : cfbb81b304ee5e27efc21adaed3EXAMPLE
Key        : clzfqEX
Version    :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDeployment](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentBatch`
<a name="codedeploy_BatchGetDeployments_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之部署的相關資訊。**  

```
Get-CDDeploymentBatch -DeploymentId d-QZMRGSTEX, d-RR0T5KTEX
```
**輸出：**  

```
ApplicationName               : CodeDeployDemoApplication
CompleteTime                  : 7/23/2015 11:26:04 PM
CreateTime                    : 7/23/2015 11:24:43 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodeDeployDemoFleet
DeploymentId                  : d-QZMRGSTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded

ApplicationName               : CodePipelineDemoApplication
CompleteTime                  : 7/23/2015 6:07:30 PM
CreateTime                    : 7/23/2015 6:06:29 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodePipelineDemoFleet
DeploymentId                  : d-RR0T5KTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchGetDeployments](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentConfig`
<a name="codedeploy_GetDeploymentConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定部署組態的摘要資訊。**  

```
Get-CDDeploymentConfig -DeploymentConfigName ThreeQuartersHealthy
```
**輸出：**  

```
CreateTime              DeploymentConfigId                      DeploymentConfigName    MinimumHealthyHosts
----------              ------------------                      --------------------    -------------------
10/3/2014 4:32:30 PM    518a3950-d034-46a1-9d2c-3c949EXAMPLE    ThreeQuartersHealthy    Amazon.CodeDeploy.Model.MinimumHealthyHosts
```
**範例 2：此範例會取得指定部署組態定義的相關資訊。**  

```
Write-Output ((Get-CDDeploymentConfig -DeploymentConfigName ThreeQuartersHealthy).MinimumHealthyHosts)
```
**輸出：**  

```
Type             Value
----             -----
FLEET_PERCENT    75
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentConfigList`
<a name="codedeploy_ListDeploymentConfigs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentConfigList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得可用部署組態的清單。**  

```
Get-CDDeploymentConfigList
```
**輸出：**  

```
ThreeQuartersHealthy
CodeDeployDefault.OneAtATime
CodeDeployDefault.AllAtOnce
CodeDeployDefault.HalfAtATime
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDeploymentConfigs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentGroup`
<a name="codedeploy_GetDeploymentGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之部署群組的相關資訊。**  

```
Get-CDDeploymentGroup -ApplicationName CodeDeployDemoApplication -DeploymentGroupName CodeDeployDemoFleet
```
**輸出：**  

```
ApplicationName              : CodeDeployDemoApplication
AutoScalingGroups            : {}
DeploymentConfigName         : CodeDeployDefault.OneAtATime
DeploymentGroupId            : 7d7c098a-b444-4b27-96ef-22791EXAMPLE
DeploymentGroupName          : CodeDeployDemoFleet
Ec2TagFilters                : {Name}
OnPremisesInstanceTagFilters : {}
ServiceRoleArn               : arn:aws:iam::80398EXAMPLE:role/CodeDeploySampleStack-4ph6EX-CodeDeployTrustRole-O9MWP7XTL8EX
TargetRevision               : Amazon.CodeDeploy.Model.RevisionLocation
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentGroupList`
<a name="codedeploy_ListDeploymentGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentGroupList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之應用程式的部署群組清單。**  

```
Get-CDDeploymentGroupList -ApplicationName CodeDeployDemoApplication
```
**輸出：**  

```
ApplicationName              DeploymentGroups                                    NextToken
---------------              ----------------                                    ---------
CodeDeployDemoApplication    {CodeDeployDemoFleet, CodeDeployProductionFleet}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDeploymentGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentInstance`
<a name="codedeploy_GetDeploymentInstance_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定部署之指定執行個體的相關資訊。**  

```
Get-CDDeploymentInstance -DeploymentId d-QZMRGSTEX -InstanceId i-254e22EX
```
**輸出：**  

```
DeploymentId    : d-QZMRGSTEX
InstanceId      : arn:aws:ec2:us-east-1:80398EXAMPLE:instance/i-254e22EX
LastUpdatedAt   : 7/23/2015 11:25:24 PM
LifecycleEvents : {ApplicationStop, DownloadBundle, BeforeInstall, Install...}
Status          : Succeeded
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDeploymentInstance](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentInstanceList`
<a name="codedeploy_ListDeploymentInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentInstanceList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之部署的執行個體 ID 清單。**  

```
Get-CDDeploymentInstanceList -DeploymentId d-QZMRGSTEX
```
**輸出：**  

```
i-254e22EX
i-274e22EX
i-3b4e22EX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDeploymentInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDDeploymentList`
<a name="codedeploy_ListDeployments_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDDeploymentList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之應用程式和部署群組的部署 ID 清單。**  

```
Get-CDDeploymentList -ApplicationName CodeDeployDemoApplication -DeploymentGroupName CodeDeployDemoFleet
```
**輸出：**  

```
d-QZMRGSTEX
d-RR0T5KTEX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDeployments](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDOnPremiseInstance`
<a name="codedeploy_GetOnPremisesInstance_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDOnPremiseInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之內部部署執行個體的相關資訊。**  

```
Get-CDOnPremiseInstance -InstanceName AssetTag12010298EX
```
**輸出：**  

```
DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX_rDH556dxEX
InstanceName   : AssetTag12010298EX
RegisterTime   : 4/3/2015 6:36:24 PM
Tags           : {Name}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDOnPremiseInstanceBatch`
<a name="codedeploy_BatchGetOnPremisesInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDOnPremiseInstanceBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例取得指定之內部部署執行個體的相關資訊。**  

```
Get-CDOnPremiseInstanceBatch -InstanceName AssetTag12010298EX, AssetTag12010298EX-2
```
**輸出：**  

```
DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployFRWUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX-2_XmeSz18rEX
InstanceName   : AssetTag12010298EX-2
RegisterTime   : 4/3/2015 6:38:52 PM
Tags           : {Name}

DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX_rDH556dxEX
InstanceName   : AssetTag12010298EX
RegisterTime   : 4/3/2015 6:36:24 PM
Tags           : {Name}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchGetOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CDOnPremiseInstanceList`
<a name="codedeploy_ListOnPremisesInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CDOnPremiseInstanceList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得可用的內部部署執行個體名稱的清單。**  

```
Get-CDOnPremiseInstanceList
```
**輸出：**  

```
AssetTag12010298EX
AssetTag12010298EX-2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CDApplication`
<a name="codedeploy_CreateApplication_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CDApplication`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立具有指定名稱的新應用程式。**  

```
New-CDApplication -ApplicationName MyNewApplication
```
**輸出：**  

```
f19e4b61-2231-4328-b0fd-e57f5EXAMPLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateApplication](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CDDeployment`
<a name="codedeploy_CreateDeployment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CDDeployment`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定的部署組態和應用程式修訂版，為指定的應用程式和部署群組建立新的部署。**  

```
New-CDDeployment -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -IgnoreApplicationStopFailures $True -S3Location_Key aws-codedeploy_linux-master.zip -RevisionType S3
```
**輸出：**  

```
d-ZHROG7UEX
```
**範例 2：此範例示範如何指定執行個體必須識別的 EC2 執行個體標籤群組，以便將執行個體包含在藍/綠部署的替代環境中。**  

```
New-CDDeployment -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -IgnoreApplicationStopFailures $True -S3Location_Key aws-codedeploy_linux-master.zip -RevisionType S3 -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
**輸出：**  

```
d-ZHROG7UEX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDeployment](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CDDeploymentConfig`
<a name="codedeploy_CreateDeploymentConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CDDeploymentConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會利用指定的名稱和行為，建立新的部署組態。**  

```
New-CDDeploymentConfig -DeploymentConfigName AtLeastTwoHealthyHosts -MinimumHealthyHosts_Type HOST_COUNT -MinimumHealthyHosts_Value 2
```
**輸出：**  

```
0f3e8187-44ef-42da-aeed-b6823EXAMPLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CDDeploymentGroup`
<a name="codedeploy_CreateDeploymentGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CDDeploymentGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例為指定的應用程式建立具有指定名稱的部署群組、Auto Scaling 群組、部署組態、標籤和服務角色。**  

```
New-CDDeploymentGroup -ApplicationName MyNewApplication -AutoScalingGroup CodeDeployDemo-ASG -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -Ec2TagFilter @{Key="Name"; Type="KEY_AND_VALUE"; Value="CodeDeployDemo"} -ServiceRoleArn arn:aws:iam::80398EXAMPLE:role/CodeDeployDemo
```
**輸出：**  

```
16bbf199-95fd-40fc-a909-0bbcfEXAMPLE
```
**範例 2：此範例示範如何指定執行個體必須識別的 EC2 執行個體標籤群組，以便將執行個體包含在藍/綠部署的替代環境中。**  

```
New-CDDeploymentGroup -ApplicationName MyNewApplication -AutoScalingGroup CodeDeployDemo-ASG -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -Ec2TagFilter @{Key="Name"; Type="KEY_AND_VALUE"; Value="CodeDeployDemo"} -ServiceRoleArn arn:aws:iam::80398EXAMPLE:role/CodeDeployDemo -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
**輸出：**  

```
16bbf199-95fd-40fc-a909-0bbcfEXAMPLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-CDApplicationRevision`
<a name="codedeploy_RegisterApplicationRevision_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-CDApplicationRevision`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的應用程式，在指定的 Amazon S3 位置註冊應用程式修訂版。**  

```
Register-CDApplicationRevision -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -S3Location_Key aws-codedeploy_linux-master.zip -Revision_RevisionType S3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterApplicationRevision](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-CDOnPremiseInstance`
<a name="codedeploy_RegisterOnPremisesInstance_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-CDOnPremiseInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定的名稱和 IAM 使用者，註冊內部部署執行個體。**  

```
Register-CDOnPremiseInstance -IamUserArn arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser -InstanceName AssetTag12010298EX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CDApplication`
<a name="codedeploy_DeleteApplication_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CDApplication`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除具有指定名稱的應用程式。繼續之前，此命令會先提示確認。新增 -Force 切換變數可刪除應用程式，無需提示。**  

```
Remove-CDApplication -ApplicationName MyNewApplication
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteApplication](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CDDeploymentConfig`
<a name="codedeploy_DeleteDeploymentConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CDDeploymentConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除具有指定名稱的部署組態。繼續之前，此命令會先提示確認。新增 -Force 切換變數可刪除部署組態，無需提示。**  

```
Remove-CDDeploymentConfig -DeploymentConfigName AtLeastTwoHealthyHosts
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CDDeploymentGroup`
<a name="codedeploy_DeleteDeploymentGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CDDeploymentGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例為指定之應用程式刪除具有指定名稱的部署群組。繼續之前，此命令會先提示確認。新增 -Force 切換變數可刪除部署群組，無需提示。**  

```
Remove-CDDeploymentGroup -ApplicationName MyNewApplication -DeploymentGroupName MyNewDeploymentGroup
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DeleteDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CDOnPremiseInstanceTag`
<a name="codedeploy_RemoveTagsFromOnPremisesInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CDOnPremiseInstanceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除具有指定名稱之內部部署執行個體的指定標籤。繼續之前，此命令會先提示確認。新增 -Force 切換變數可刪除標籤，無需提示。**  

```
Remove-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveTagsFromOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-CDDeployment`
<a name="codedeploy_StopDeployment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-CDDeployment`。

**Tools for PowerShell V5**  
**範例 1：此範例會嘗試使用指定的部署 ID 停止部署。**  

```
Stop-CDDeployment -DeploymentId d-LJQNREYEX
```
**輸出：**  

```
Status     StatusMessage
------     -------------
Pending    Stopping Pending. Stopping to schedule commands in the deployment instances
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopDeployment](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-CDOnPremiseInstance`
<a name="codedeploy_DeregisterOnPremisesInstance_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-CDOnPremiseInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例使用指定的名稱取消註冊內部部署執行個體。**  

```
Unregister-CDOnPremiseInstance -InstanceName AssetTag12010298EX
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CDApplication`
<a name="codedeploy_UpdateApplication_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CDApplication`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更指定的應用程式名稱。**  

```
Update-CDApplication -ApplicationName MyNewApplication -NewApplicationName MyNewApplication-2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateApplication](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CDDeploymentGroup`
<a name="codedeploy_UpdateDeploymentGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CDDeploymentGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更指定應用程式之指定部署群組的名稱。**  

```
Update-CDDeploymentGroup -ApplicationName MyNewApplication -CurrentDeploymentGroupName MyNewDeploymentGroup -NewDeploymentGroupName MyNewDeploymentGroup-2
```
**範例 2：此範例示範如何指定執行個體必須識別的 EC2 執行個體標籤群組，以便將執行個體包含在藍/綠部署的替代環境中。**  

```
Update-CDDeploymentGroup -ApplicationName MyNewApplication -CurrentDeploymentGroupName MyNewDeploymentGroup -NewDeploymentGroupName MyNewDeploymentGroup-2 -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 CodePipeline 範例
<a name="powershell_codepipeline_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 CodePipeline 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Confirm-CPJob`
<a name="codepipeline_AcknowledgeJob_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Confirm-CPJob`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得任務的狀態。**  

```
Confirm-CPJob -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE -Nonce 3
```
**輸出：**  

```
Value
-----
InProgress
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AcknowledgeJob](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-CPStageTransition`
<a name="codepipeline_DisableStageTransition_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-CPStageTransition`。

**Tools for PowerShell V5**  
**範例 1：此範例會停用指定管道中指定階段的傳入轉換。**  

```
Disable-CPStageTransition -PipelineName CodePipelineDemo -Reason "Disabling temporarily." -StageName Beta -TransitionType Inbound
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableStageTransition](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-CPStageTransition`
<a name="codepipeline_EnableStageTransition_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-CPStageTransition`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用指定管道中指定階段的傳入轉換。**  

```
Enable-CPStageTransition -PipelineName CodePipelineDemo -StageName Beta -TransitionType Inbound
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableStageTransition](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CPActionType`
<a name="codepipeline_ListActionTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CPActionType`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之擁有者所有可用動作的相關資訊。**  

```
ForEach ($actionType in (Get-CPActionType -ActionOwnerFilter AWS)) {
  Write-Output ("For Category = " + $actionType.Id.Category + ", Owner = " + $actionType.Id.Owner + ", Provider = " + $actionType.Id.Provider + ", Version = " + $actionType.Id.Version + ":")
  Write-Output ("  ActionConfigurationProperties:")
  ForEach ($acp in $actionType.ActionConfigurationProperties) {
    Write-Output ("    For " + $acp.Name + ":")
    Write-Output ("      Description = " + $acp.Description)
    Write-Output ("      Key = " + $acp.Key)
    Write-Output ("      Queryable = " + $acp.Queryable)
    Write-Output ("      Required = " + $acp.Required)
    Write-Output ("      Secret = " + $acp.Secret)
  }
  Write-Output ("  InputArtifactDetails:")
  Write-Output ("    MaximumCount = " + $actionType.InputArtifactDetails.MaximumCount)
  Write-Output ("    MinimumCount = " + $actionType.InputArtifactDetails.MinimumCount)
  Write-Output ("  OutputArtifactDetails:")
  Write-Output ("    MaximumCount = " + $actionType.OutputArtifactDetails.MaximumCount)
  Write-Output ("    MinimumCount = " + $actionType.OutputArtifactDetails.MinimumCount)
  Write-Output ("  Settings:")
  Write-Output ("    EntityUrlTemplate = " + $actionType.Settings.EntityUrlTemplate)
  Write-Output ("    ExecutionUrlTemplate = " + $actionType.Settings.ExecutionUrlTemplate)
}
```
**輸出：**  

```
For Category = Deploy, Owner = AWS, Provider = ElasticBeanstalk, Version = 1:
  ActionConfigurationProperties:
    For ApplicationName:
      Description = The AWS Elastic Beanstalk Application name
      Key = True
      Queryable = False
      Required = True
      Secret = False
    For EnvironmentName:
      Description = The AWS Elastic Beanstalk Environment name
      Key = True
      Queryable = False
      Required = True
      Secret = False
  InputArtifactDetails:
    MaximumCount = 1
    MinimumCount = 1
  OutputArtifactDetails:
    MaximumCount = 0
    MinimumCount = 0
  Settings:
    EntityUrlTemplate = https://console.aws.amazon.com/elasticbeanstalk/r/application/{Config:ApplicationName}
    ExecutionUrlTemplate = https://console.aws.amazon.com/elasticbeanstalk/r/application/{Config:ApplicationName} 
For Category = Deploy, Owner = AWS, Provider = CodeDeploy, Version = 1:
  ActionConfigurationProperties:
    For ApplicationName:
      Description = The AWS CodeDeploy Application name
      Key = True
      Queryable = False
      Required = True
      Secret = False
    For DeploymentGroupName:
      Description = The AWS CodeDeploy Deployment Group name
      Key = True
      Queryable = False
      Required = True
      Secret = False
  InputArtifactDetails:
    MaximumCount = 1
    MinimumCount = 1
  OutputArtifactDetails:
    MaximumCount = 0
    MinimumCount = 0
  Settings:
    EntityUrlTemplate = https://console.aws.amazon.com/codedeploy/home?#/applications/{Config:ApplicationName}/deployment-groups/{Config:DeploymentGroupName}
    ExecutionUrlTemplate = https://console.aws.amazon.com/codedeploy/home?#/deployments/{ExternalExecutionId}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListActionTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CPActionableJobList`
<a name="codepipeline_PollForJobs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CPActionableJobList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定動作類別、擁有者、提供者、版本和查詢參數之所有可行任務的相關資訊。**  

```
Get-CPActionableJobList -ActionTypeId_Category Build -ActionTypeId_Owner Custom -ActionTypeId_Provider MyCustomProviderName -ActionTypeId_Version 1 -QueryParam @{"ProjectName" = "MyProjectName"}
```
**輸出：**  

```
AccountId       Data                                 Id                                      Nonce
---------       ----                                 --                                      -----
80398EXAMPLE    Amazon.CodePipeline.Model.JobData    0de392f5-712d-4f41-ace3-f57a0EXAMPLE    3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PollForJobs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CPJobDetail`
<a name="codepipeline_GetJobDetails_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CPJobDetail`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定任務的一般資訊。**  

```
Get-CPJobDetail -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE
```
**輸出：**  

```
AccountId       Data                                 Id
---------       ----                                 --
80398EXAMPLE    Amazon.CodePipeline.Model.JobData    f570dc12-5ef3-44bc-945a-6e133EXAMPLE
```
**範例 2：此範例會取得指定任務的詳細資訊。**  

```
$jobDetails = Get-CPJobDetail -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE
Write-Output ("For Job " + $jobDetails.Id + ":")
Write-Output ("  AccountId = " + $jobDetails.AccountId)
$jobData = $jobDetails.Data
Write-Output ("  Configuration:")
ForEach ($key in $jobData.ActionConfiguration.Keys) {
  $value = $jobData.ActionConfiguration.$key
  Write-Output ("    " + $key + " = " + $value)
}
Write-Output ("  ActionTypeId:")
Write-Output ("    Category = " + $jobData.ActionTypeId.Category)
Write-Output ("    Owner = " + $jobData.ActionTypeId.Owner)
Write-Output ("    Provider = " + $jobData.ActionTypeId.Provider)
Write-Output ("    Version = " + $jobData.ActionTypeId.Version)
Write-Output ("  ArtifactCredentials:")
Write-Output ("    AccessKeyId = " + $jobData.ArtifactCredentials.AccessKeyId)
Write-Output ("    SecretAccessKey = " + $jobData.ArtifactCredentials.SecretAccessKey)
Write-Output ("    SessionToken = " + $jobData.ArtifactCredentials.SessionToken)
Write-Output ("  InputArtifacts:")
ForEach ($ia in $jobData.InputArtifacts) {
  Write-Output ("    " + $ia.Name)
}
Write-Output ("  OutputArtifacts:")
ForEach ($oa in $jobData.OutputArtifacts) {
  Write-Output ("    " + $oa.Name)
}
Write-Output ("  PipelineContext:")
$context = $jobData.PipelineContext
Write-Output ("    Name = " + $context.Action.Name)
Write-Output ("    PipelineName = " + $context.PipelineName)
Write-Output ("    Stage = " + $context.Stage.Name)
```
**輸出：**  

```
For Job f570dc12-5ef3-44bc-945a-6e133EXAMPLE:
  AccountId = 80398EXAMPLE
  Configuration:
  ActionTypeId:
    Category = Build
    Owner = Custom
    Provider = MyCustomProviderName
    Version = 1
  ArtifactCredentials:
    AccessKeyId = ASIAIEI3...IXI6YREX
    SecretAccessKey = cqAFDhEi...RdQyfa2u
    SessionToken = AQoDYXdz...5u+lsAU=
  InputArtifacts:
    MyApp
  OutputArtifacts:
    MyAppBuild
  PipelineContext:
    Name = Build
    PipelineName = CodePipelineDemo
    Stage = Build
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetJobDetails](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CPPipeline`
<a name="codepipeline_GetPipeline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CPPipeline`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定管道的一般資訊。**  

```
Get-CPPipeline -Name CodePipelineDemo -Version 1
```
**輸出：**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {Source, Build, Beta, TestStage}
Version       : 1
```
**範例 2：此範例會取得指定管道的詳細資訊。**  

```
$pipeline = Get-CPPipeline -Name CodePipelineDemo
Write-Output ("Name = " + $pipeline.Name)
Write-Output ("RoleArn = " + $pipeline.RoleArn)
Write-Output ("Version = " + $pipeline.Version)
Write-Output ("ArtifactStore:")
Write-Output ("  Location = " + $pipeline.ArtifactStore.Location)
Write-Output ("  Type = " + $pipeline.ArtifactStore.Type.Value)
Write-Output ("Stages:")
ForEach ($stage in $pipeline.Stages) {
  Write-Output ("  Name = " + $stage.Name)
  Write-Output ("    Actions:")
  ForEach ($action in $stage.Actions) {
    Write-Output ("      Name = " + $action.Name)
	Write-Output ("        Category = " + $action.ActionTypeId.Category)
	Write-Output ("        Owner = " + $action.ActionTypeId.Owner)
	Write-Output ("        Provider = " + $action.ActionTypeId.Provider)
	Write-Output ("        Version = " + $action.ActionTypeId.Version)
	Write-Output ("        Configuration:")
	ForEach ($key in $action.Configuration.Keys) {
	  $value = $action.Configuration.$key
	  Write-Output ("          " + $key + " = " + $value)
	}
	Write-Output ("        InputArtifacts:")
	ForEach ($ia in $action.InputArtifacts) {
	  Write-Output ("          " + $ia.Name)
	}
	ForEach ($oa in $action.OutputArtifacts) {
	  Write-Output ("          " + $oa.Name)
	}
	Write-Output ("        RunOrder = " + $action.RunOrder)
  }
}
```
**輸出：**  

```
Name = CodePipelineDemo
RoleArn = arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Version = 3
ArtifactStore:
  Location = amzn-s3-demo-bucket
  Type = S3
Stages:
  Name = Source
    Actions:
      Name = Source
        Category = Source
        Owner = ThirdParty
        Provider = GitHub
        Version = 1
        Configuration:
          Branch = master
          OAuthToken = ****
          Owner = my-user-name
          Repo = MyRepoName
        InputArtifacts:
          MyApp
        RunOrder = 1
  Name = Build
    Actions:
      Name = Build
        Category = Build
        Owner = Custom
        Provider = MyCustomProviderName
        Version = 1
        Configuration:
          ProjectName = MyProjectName
        InputArtifacts:
          MyApp
          MyAppBuild
        RunOrder = 1
  Name = Beta
    Actions:
      Name = CodePipelineDemoFleet
        Category = Deploy
        Owner = AWS
        Provider = CodeDeploy
        Version = 1
        Configuration:
          ApplicationName = CodePipelineDemoApplication
          DeploymentGroupName = CodePipelineDemoFleet
        InputArtifacts:
          MyAppBuild
        RunOrder = 1
  Name = TestStage
    Actions:
      Name = MyJenkinsTestAction
        Category = Test
        Owner = Custom
        Provider = MyCustomTestProvider
        Version = 1
        Configuration:
          ProjectName = MyJenkinsProjectName
        InputArtifacts:
          MyAppBuild
        RunOrder = 1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPipeline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CPPipelineList`
<a name="codepipeline_ListPipelines_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CPPipelineList`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得可用管道的清單。**  

```
Get-CPPipelineList
```
**輸出：**  

```
Created                  Name                Updated                  Version
-------                  ----                -------                  -------
8/13/2015 10:17:54 PM    CodePipelineDemo    8/13/2015 10:17:54 PM    3
7/8/2015 2:41:53 AM      MyFirstPipeline     7/22/2015 9:06:37 PM     7
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListPipelines](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CPPipelineState`
<a name="codepipeline_GetPipelineState_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CPPipelineState`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之管道階段的一般資訊。**  

```
Get-CPPipelineState -Name CodePipelineDemo
```
**輸出：**  

```
Created         : 8/13/2015 10:17:54 PM
PipelineName    : CodePipelineDemo
PipelineVersion : 1
StageStates     : {Source, Build, Beta, TestStage}
Updated         : 8/13/2015 10:17:54 PM
```
**範例 2：此範例會取得指定之管道狀態的詳細資訊。**  

```
ForEach ($stageState in (Get-CPPipelineState -Name $arg).StageStates) {
  Write-Output ("For " + $stageState.StageName + ":")
  Write-Output ("  InboundTransitionState:")
  Write-Output ("    DisabledReason = " + $stageState.InboundTransitionState.DisabledReason)
  Write-Output ("    Enabled = " + $stageState.InboundTransitionState.Enabled)
  Write-Output ("    LastChangedAt = " + $stageState.InboundTransitionState.LastChangedAt)
  Write-Output ("    LastChangedBy = " + $stageState.InboundTransitionState.LastChangedBy)
  Write-Output ("  ActionStates:")
  ForEach ($actionState in $stageState.ActionStates) {
    Write-Output ("    For " + $actionState.ActionName + ":")
	Write-Output ("      CurrentRevision:")
    Write-Output ("        Created = " + $actionState.CurrentRevision.Created)
	Write-Output ("        RevisionChangeId = " + $actionState.CurrentRevision.RevisionChangeId)
	Write-Output ("        RevisionId = " + $actionState.CurrentRevision.RevisionId)
	Write-Output ("      EntityUrl = " + $actionState.EntityUrl)
	Write-Output ("      LatestExecution:")
    Write-Output ("        ErrorDetails:")
    Write-Output ("          Code = " + $actionState.LatestExecution.ErrorDetails.Code)
	Write-Output ("          Message = " + $actionState.LatestExecution.ErrorDetails.Message)
	Write-Output ("        ExternalExecutionId = " + $actionState.LatestExecution.ExternalExecutionId)
	Write-Output ("        ExternalExecutionUrl = " + $actionState.LatestExecution.ExternalExecutionUrl)
	Write-Output ("        LastStatusChange	= " + $actionState.LatestExecution.LastStatusChange)
	Write-Output ("        PercentComplete = " + $actionState.LatestExecution.PercentComplete)
	Write-Output ("        Status = " + $actionState.LatestExecution.Status)
	Write-Output ("        Summary = " + $actionState.LatestExecution.Summary)
	Write-Output ("      RevisionUrl = " + $actionState.RevisionUrl)
  }
}
```
**輸出：**  

```
For Source:
  InboundTransitionState:
    DisabledReason =
    Enabled =
    LastChangedAt =
    LastChangedBy =
  ActionStates:
    For Source:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = https://github.com/my-user-name/MyRepoName/tree/master
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId =
        ExternalExecutionUrl =
        LastStatusChange = 07/20/2015 23:28:45
        PercentComplete = 0
        Status = Succeeded
        Summary =
      RevisionUrl =
For Build:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For Build:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = http://54.174.131.1EX/job/MyJenkinsDemo
      LatestExecution:
        ErrorDetails:
          Code = TimeoutError
          Message = The action failed because a job worker exceeded its time limit. If this is a custom action, make sure that the job worker is configured correctly.
        ExternalExecutionId =
        ExternalExecutionUrl =
        LastStatusChange = 07/21/2015 00:29:29
        PercentComplete = 0
        Status = Failed
        Summary =
      RevisionUrl =
For Beta:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For CodePipelineDemoFleet:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = https://console.aws.amazon.com/codedeploy/home?#/applications/CodePipelineDemoApplication/deployment-groups/CodePipelineDemoFleet
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId = d-D5LTCZXEX
        ExternalExecutionUrl = https://console.aws.amazon.com/codedeploy/home?#/deployments/d-D5LTCZXEX
        LastStatusChange = 07/08/2015 22:07:42
        PercentComplete = 0
        Status = Succeeded
        Summary = Deployment Succeeded
      RevisionUrl =
For TestStage:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For MyJenkinsTestAction25:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = http://54.174.131.1EX/job/MyJenkinsDemo
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId = 5
        ExternalExecutionUrl = http://54.174.131.1EX/job/MyJenkinsDemo/5
        LastStatusChange = 07/08/2015 22:09:03
        PercentComplete = 0
        Status = Succeeded
        Summary = Finished
      RevisionUrl =
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPipelineState](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CPCustomActionType`
<a name="codepipeline_CreateCustomActionType_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CPCustomActionType`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定的屬性建立新的自訂動作。**  

```
New-CPCustomActionType -Category Build -ConfigurationProperty @{"Description" = "The name of the build project must be provided when this action is added to the pipeline."; "Key" = $True; "Name" = "ProjectName"; "Queryable" = $False; "Required" = $True; "Secret" = $False; "Type" = "String"} -Settings_EntityUrlTemplate "https://my-build-instance/job/{Config:ProjectName}/" -Settings_ExecutionUrlTemplate "https://my-build-instance/job/mybuildjob/lastSuccessfulBuild{ExternalExecutionId}/" -InputArtifactDetails_MaximumCount 1 -OutputArtifactDetails_MaximumCount 1 -InputArtifactDetails_MinimumCount 0 -OutputArtifactDetails_MinimumCount 0 -Provider "MyBuildProviderName" -Version 1
```
**輸出：**  

```
ActionConfigurationProperties : {ProjectName}
Id                            : Amazon.CodePipeline.Model.ActionTypeId
InputArtifactDetails          : Amazon.CodePipeline.Model.ArtifactDetails
OutputArtifactDetails         : Amazon.CodePipeline.Model.ArtifactDetails
Settings                      : Amazon.CodePipeline.Model.ActionTypeSettings
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateCustomActionType](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CPPipeline`
<a name="codepipeline_CreatePipeline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CPPipeline`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定的設定來建立新的管道。**  

```
$pipeline = New-Object Amazon.CodePipeline.Model.PipelineDeclaration

$sourceStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration
$deployStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration

$sourceStageActionOutputArtifact = New-Object Amazon.CodePipeline.Model.OutputArtifact
$sourceStageActionOutputArtifact.Name = "MyApp"

$sourceStageAction.ActionTypeId = @{"Category" = "Source"; "Owner" = "AWS"; "Provider" = "S3"; "Version" = 1}
$sourceStageAction.Configuration.Add("S3Bucket", "amzn-s3-demo-bucket")
$sourceStageAction.Configuration.Add("S3ObjectKey", "my-object-key-name.zip")
$sourceStageAction.OutputArtifacts.Add($sourceStageActionOutputArtifact)
$sourceStageAction.Name = "Source"

$deployStageActionInputArtifact = New-Object Amazon.CodePipeline.Model.InputArtifact
$deployStageActionInputArtifact.Name = "MyApp"

$deployStageAction.ActionTypeId = @{"Category" = "Deploy"; "Owner" = "AWS"; "Provider" = "CodeDeploy"; "Version" = 1}
$deployStageAction.Configuration.Add("ApplicationName", "CodePipelineDemoApplication")
$deployStageAction.Configuration.Add("DeploymentGroupName", "CodePipelineDemoFleet")
$deployStageAction.InputArtifacts.Add($deployStageActionInputArtifact)
$deployStageAction.Name = "CodePipelineDemoFleet"

$sourceStage = New-Object Amazon.CodePipeline.Model.StageDeclaration
$deployStage = New-Object Amazon.CodePipeline.Model.StageDeclaration

$sourceStage.Name = "Source"
$deployStage.Name = "Beta"

$sourceStage.Actions.Add($sourceStageAction)
$deployStage.Actions.Add($deployStageAction)

$pipeline.ArtifactStore = @{"Location" = "amzn-s3-demo-bucket"; "Type" = "S3"}
$pipeline.Name = "CodePipelineDemo"
$pipeline.RoleArn = "arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole"
$pipeline.Stages.Add($sourceStage)
$pipeline.Stages.Add($deployStage)
$pipeline.Version = 1

New-CPPipeline -Pipeline $pipeline
```
**輸出：**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {Source, Beta}
Version       : 1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreatePipeline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CPCustomActionType`
<a name="codepipeline_DeleteCustomActionType_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CPCustomActionType`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的自訂動作。繼續之前，此命令會先提示確認。新增 -Force 切換變數可刪除自訂動作，無需提示。**  

```
Remove-CPCustomActionType -Category Build -Provider MyBuildProviderName -Version 1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteCustomActionType](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CPPipeline`
<a name="codepipeline_DeletePipeline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CPPipeline`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的管道。繼續之前，此命令會先提示確認。新增 -Force 切換變數可刪除管道，無需提示。**  

```
Remove-CPPipeline -Name CodePipelineDemo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeletePipeline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-CPPipelineExecution`
<a name="codepipeline_StartPipelineExecution_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-CPPipelineExecution`。

**Tools for PowerShell V5**  
**範例 1：此範例會開始執行指定的管道。**  

```
Start-CPPipelineExecution -Name CodePipelineDemo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartPipelineExecution](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CPPipeline`
<a name="codepipeline_UpdatePipeline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CPPipeline`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定的設定來更新指定的現有管道。**  

```
$pipeline = New-Object Amazon.CodePipeline.Model.PipelineDeclaration

$sourceStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration
$deployStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration

$sourceStageActionOutputArtifact = New-Object Amazon.CodePipeline.Model.OutputArtifact
$sourceStageActionOutputArtifact.Name = "MyApp"

$sourceStageAction.ActionTypeId = @{"Category" = "Source"; "Owner" = "AWS"; "Provider" = "S3"; "Version" = 1}
$sourceStageAction.Configuration.Add("S3Bucket", "amzn-s3-demo-bucket")
$sourceStageAction.Configuration.Add("S3ObjectKey", "my-object-key-name.zip")
$sourceStageAction.OutputArtifacts.Add($sourceStageActionOutputArtifact)
$sourceStageAction.Name = "Source"

$deployStageActionInputArtifact = New-Object Amazon.CodePipeline.Model.InputArtifact
$deployStageActionInputArtifact.Name = "MyApp"

$deployStageAction.ActionTypeId = @{"Category" = "Deploy"; "Owner" = "AWS"; "Provider" = "CodeDeploy"; "Version" = 1}
$deployStageAction.Configuration.Add("ApplicationName", "CodePipelineDemoApplication")
$deployStageAction.Configuration.Add("DeploymentGroupName", "CodePipelineDemoFleet")
$deployStageAction.InputArtifacts.Add($deployStageActionInputArtifact)
$deployStageAction.Name = "CodePipelineDemoFleet"

$sourceStage = New-Object Amazon.CodePipeline.Model.StageDeclaration
$deployStage = New-Object Amazon.CodePipeline.Model.StageDeclaration

$sourceStage.Name = "MyInputFiles"
$deployStage.Name = "MyTestDeployment"

$sourceStage.Actions.Add($sourceStageAction)
$deployStage.Actions.Add($deployStageAction)

$pipeline.ArtifactStore = @{"Location" = "amzn-s3-demo-bucket"; "Type" = "S3"}
$pipeline.Name = "CodePipelineDemo"
$pipeline.RoleArn = "arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole"
$pipeline.Stages.Add($sourceStage)
$pipeline.Stages.Add($deployStage)
$pipeline.Version = 1

Update-CPPipeline -Pipeline $pipeline
```
**輸出：**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {InputFiles, TestDeployment}
Version       : 2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdatePipeline](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon Cognito 身分範例
<a name="powershell_cognito-identity_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon Cognito Identity 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-CGIIdentityPool`
<a name="cognito-identity_DescribeIdentityPool_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CGIIdentityPool`。

**Tools for PowerShell V5**  
**範例 1：依照特定身分集區 ID 順序擷取其相關資訊。**  

```
Get-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
**輸出：**  

```
LoggedAt                       : 8/12/2015 4:29:40 PM
AllowUnauthenticatedIdentities : True
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
IdentityPoolName               : CommonTests1
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 142
HttpStatusCode                 : OK
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CGIIdentityPoolList`
<a name="cognito-identity_ListIdentityPools_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CGIIdentityPoolList`。

**Tools for PowerShell V5**  
**範例 1：擷取現有身分集區的清單。**  

```
Get-CGIIdentityPoolList
```
**輸出：**  

```
IdentityPoolId                                                     IdentityPoolName
--------------                                                     ----------------
us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1                     CommonTests1
us-east-1:118d242d-204e-4b88-b803-EXAMPLEGUID2                     Tests2
us-east-1:15d49393-ab16-431a-b26e-EXAMPLEGUID3                     CommonTests13
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListIdentityPools](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CGIIdentityPoolRole`
<a name="cognito-identity_GetIdentityPoolRoles_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CGIIdentityPoolRole`。

**Tools for PowerShell V5**  
**範例 1：取得特定身分集區角色的相關資訊。**  

```
Get-CGIIdentityPoolRole -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
**輸出：**  

```
LoggedAt         : 8/12/2015 4:33:51 PM
IdentityPoolId   : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
Roles            : {[unauthenticated, arn:aws:iam::123456789012:role/CommonTests1Role]}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 165
HttpStatusCode   : OK
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-CGIIdentityPool`
<a name="cognito-identity_CreateIdentityPool_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-CGIIdentityPool`。

**Tools for PowerShell V5**  
**範例 1：建立新的身分集區，該身分集區允許未驗證的身分。**  

```
New-CGIIdentityPool -AllowUnauthenticatedIdentities $true -IdentityPoolName CommonTests13
```
**輸出：**  

```
LoggedAt                       : 8/12/2015 4:56:07 PM
AllowUnauthenticatedIdentities : True
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:15d49393-ab16-431a-b26e-EXAMPLEGUID3
IdentityPoolName               : CommonTests13
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 136
HttpStatusCode                 : OK
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CGIIdentityPool`
<a name="cognito-identity_DeleteIdentityPool_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CGIIdentityPool`。

**Tools for PowerShell V5**  
**範例 1：刪除特定身分集區。**  

```
Remove-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-CGIIdentityPoolRole`
<a name="cognito-identity_SetIdentityPoolRoles_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-CGIIdentityPoolRole`。

**Tools for PowerShell V5**  
**範例 1：將特定身分集區設定為具有未驗證的 IAM 角色。**  

```
Set-CGIIdentityPoolRole -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1 -Role @{ "unauthenticated" = "arn:aws:iam::123456789012:role/CommonTests1Role" }
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-CGIIdentityPool`
<a name="cognito-identity_UpdateIdentityPool_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-CGIIdentityPool`。

**Tools for PowerShell V5**  
**範例 1：更新一些身分集區屬性，在此案例為身分集區的名稱。**  

```
Update-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1 -IdentityPoolName NewPoolName
```
**輸出：**  

```
LoggedAt                       : 8/12/2015 4:53:33 PM
AllowUnauthenticatedIdentities : False
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
IdentityPoolName               : NewPoolName
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 135
HttpStatusCode                 : OK
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS Config 使用 Tools for PowerShell V5 的範例
<a name="powershell_config-service_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS Config。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-CFGResourceTag`
<a name="config-service_TagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-CFGResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的標籤與資源 ARN 相關聯，在此案例為 config-rule/config-rule-16iyn0。**  

```
Add-CFGResourceTag -ResourceArn arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-16iyn0 -Tag @{Key="Release";Value="Beta"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregateComplianceByConfigRuleList`
<a name="config-service_DescribeAggregateComplianceByConfigRules_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregateComplianceByConfigRuleList`。

**Tools for PowerShell V5**  
**範例 1：此範例會從給定 Config 規則的 ConfigurationAggregator 'kaju' 篩選條件中擷取詳細資訊，並展開/傳回規則的 'Compliance'。**  

```
Get-CFGAggregateComplianceByConfigRuleList -ConfigurationAggregatorName kaju -Filters_ConfigRuleName ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK | Select-Object -ExpandProperty Compliance
```
**輸出：**  

```
ComplianceContributorCount                            ComplianceType
--------------------------                            --------------
Amazon.ConfigService.Model.ComplianceContributorCount NON_COMPLIANT
```
**範例 2：此範例會從給定的 ConfigurationAggregator 擷取詳細資訊，針對彙總工具涵蓋的所有區域的給定帳戶進行篩選，並進一步傳回所有規則的合規性。**  

```
Get-CFGAggregateComplianceByConfigRuleList -ConfigurationAggregatorName kaju -Filters_AccountId 123456789012 | Select-Object ConfigRuleName, @{N="Compliance";E={$_.Compliance.ComplianceType}}
```
**輸出：**  

```
ConfigRuleName                      Compliance
--------------                      ----------
ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK NON_COMPLIANT
ec2-instance-no-public-ip           NON_COMPLIANT
desired-instance-type               NON_COMPLIANT
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAggregateComplianceByConfigRules](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregateComplianceDetailsByConfigRule`
<a name="config-service_GetAggregateComplianceDetailsByConfigRule_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregateComplianceDetailsByConfigRule`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回評估結果，針對指定帳戶、彙總工具、區域和組態規則處於「COMPLIANT」狀態的 AWS Config 規則「desired-instance-type」，選取具有 resource-id 和 resource-type 的輸出**  

```
Get-CFGAggregateComplianceDetailsByConfigRule -AccountId 123456789012 -AwsRegion eu-west-1 -ComplianceType COMPLIANT -ConfigRuleName desired-instance-type -ConfigurationAggregatorName raju | Select-Object -ExpandProperty EvaluationResultIdentifier | Select-Object -ExpandProperty EvaluationResultQualifier
```
**輸出：**  

```
ConfigRuleName        ResourceId          ResourceType
--------------        ----------          ------------
desired-instance-type i-0f1bf2f34c5678d12 AWS::EC2::Instance
desired-instance-type i-0fd12dd3456789123 AWS::EC2::Instance
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAggregateComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregateConfigRuleComplianceSummary`
<a name="config-service_GetAggregateConfigRuleComplianceSummary_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregateConfigRuleComplianceSummary`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回給定彙總工具的不合規規則數目。**  

```
(Get-CFGAggregateConfigRuleComplianceSummary -ConfigurationAggregatorName raju).AggregateComplianceCounts.ComplianceSummary.NonCompliantResourceCount
```
**輸出：**  

```
CapExceeded CappedCount
----------- -----------
False       5
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAggregateConfigRuleComplianceSummary](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregateDiscoveredResourceCount`
<a name="config-service_GetAggregateDiscoveredResourceCounts_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregateDiscoveredResourceCount`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回針對區域 us-east-1 篩選之給定彙總工具的資源計數。**  

```
Get-CFGAggregateDiscoveredResourceCount -ConfigurationAggregatorName Master -Filters_Region us-east-1
```
**輸出：**  

```
GroupByKey GroupedResourceCounts NextToken TotalDiscoveredResources
---------- --------------------- --------- ------------------------
           {}                              455
```
**範例 2：此範例會傳回給定彙總工具之篩選區域之依 RESOURCE\$1TYPE 分組的資源計數。**  

```
Get-CFGAggregateDiscoveredResourceCount -ConfigurationAggregatorName Master -Filters_Region us-east-1 -GroupByKey RESOURCE_TYPE | 
			Select-Object -ExpandProperty GroupedResourceCounts
```
**輸出：**  

```
GroupName                          ResourceCount
---------                          -------------
AWS::CloudFormation::Stack         12
AWS::CloudFront::Distribution      1
AWS::CloudTrail::Trail             1
AWS::DynamoDB::Table               1
AWS::EC2::EIP                      2
AWS::EC2::FlowLog                  2
AWS::EC2::InternetGateway          4
AWS::EC2::NatGateway               2
AWS::EC2::NetworkAcl               4
AWS::EC2::NetworkInterface         12
AWS::EC2::RouteTable               13
AWS::EC2::SecurityGroup            18
AWS::EC2::Subnet                   16
AWS::EC2::VPC                      4
AWS::EC2::VPCEndpoint              2
AWS::EC2::VPCPeeringConnection     1
AWS::IAM::Group                    2
AWS::IAM::Policy                   51
AWS::IAM::Role                     78
AWS::IAM::User                     7
AWS::Lambda::Function              3
AWS::RDS::DBSecurityGroup          1
AWS::S3::Bucket                    3
AWS::SSM::AssociationCompliance    107
AWS::SSM::ManagedInstanceInventory 108
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAggregateDiscoveredResourceCounts](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregateDiscoveredResourceList`
<a name="config-service_ListAggregateDiscoveredResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregateDiscoveredResourceList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 'Ireland' 彙總工具中彙總之給定資源類型的資源識別碼。如需資源類型的清單，請參閱 https://docs.aws.amazon.com/sdkfornet/v4/apidocs/index.html?page=ConfigService/TConfigServiceResourceType.html&tocid=Amazon\$1ConfigService\$1ResourceType。**  

```
Get-CFGAggregateDiscoveredResourceList -ConfigurationAggregatorName Ireland -ResourceType ([Amazon.ConfigService.ResourceType]::AWSAutoScalingAutoScalingGroup)
```
**輸出：**  

```
ResourceId      : arn:aws:autoscaling:eu-west-1:123456789012:autoScalingGroup:12e3b4fc-1234-1234-a123-1d2ba3c45678:autoScalingGroupName/asg-1
ResourceName    : asg-1
ResourceType    : AWS::AutoScaling::AutoScalingGroup
SourceAccountId : 123456789012
SourceRegion    : eu-west-1
```
**範例 2：此範例傳回使用 region us-east-1 篩選之給定彙總工具的名為 'default' 的資源類型 `AwsEC2SecurityGroup`。**  

```
Get-CFGAggregateDiscoveredResourceList -ConfigurationAggregatorName raju -ResourceType ([Amazon.ConfigService.ResourceType]::AWSEC2SecurityGroup) -Filters_Region us-east-1 -Filters_ResourceName default
```
**輸出：**  

```
ResourceId      : sg-01234bd5dbfa67c89
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1

ResourceId      : sg-0123a4ebbf56789be
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1

ResourceId      : sg-4fc1d234
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAggregateDiscoveredResources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregateResourceConfig`
<a name="config-service_GetAggregateResourceconfig-service_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregateResourceConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例針對彙整之給定資源傳回組態項目，並展開組態。**  

```
(Get-CFGAggregateResourceConfig -ResourceIdentifier_SourceRegion us-east-1 -ResourceIdentifier_SourceAccountId 123456789012 -ResourceIdentifier_ResourceId sg-4fc1d234 -ResourceIdentifier_ResourceType ([Amazon.ConfigService.ResourceType]::AWSEC2SecurityGroup) -ConfigurationAggregatorName raju).Configuration | ConvertFrom-Json
```
**輸出：**  

```
{"description":"default VPC security group","groupName":"default","ipPermissions":[{"ipProtocol":"-1","ipv6Ranges":[],"prefixListIds":[],"userIdGroupPairs":[{"groupId":"sg-4fc1d234","userId":"123456789012"}],"ipv4Ranges":[],"ipRanges":[]},{"fromPort":3389,"ipProtocol":"tcp","ipv6Ranges":[],"prefixListIds":[],"toPort":3389,"userIdGroupPairs":[],"ipv4Ranges":[{"cidrIp":"54.240.197.224/29","description":"office subnet"},{"cidrIp":"72.21.198.65/32","description":"home pc"}],"ipRanges":["54.240.197.224/29","72.21.198.65/32"]}],"ownerId":"123456789012","groupId":"sg-4fc1d234","ipPermissionsEgress":[{"ipProtocol":"-1","ipv6Ranges":[],"prefixListIds":[],"userIdGroupPairs":[],"ipv4Ranges":[{"cidrIp":"0.0.0.0/0"}],"ipRanges":["0.0.0.0/0"]}],"tags":[],"vpcId":"vpc-2d1c2e34"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAggregateResourceconfig-service](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregateResourceConfigBatch`
<a name="config-service_BatchGetAggregateResourceconfig-service_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregateResourceConfigBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會針對給定彙總工具中存在的資源 (已識別)，擷取目前的組態項目。**  

```
$resIdentifier=[Amazon.ConfigService.Model.AggregateResourceIdentifier]@{
		ResourceId= "i-012e3cb4df567e8aa"
		ResourceName = "arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa"
		ResourceType = [Amazon.ConfigService.ResourceType]::AWSEC2Instance
		SourceAccountId = "123456789012"
		SourceRegion = "eu-west-1"
	}
		
	Get-CFGAggregateResourceConfigBatch -ResourceIdentifier $resIdentifier -ConfigurationAggregatorName raju
```
**輸出：**  

```
BaseConfigurationItems UnprocessedResourceIdentifiers
---------------------- ------------------------------
{}                     {arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchGetAggregateResourceconfig-service](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGAggregationAuthorizationList`
<a name="config-service_DescribeAggregationAuthorizations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGAggregationAuthorizationList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取授予彙總工具的授權。**  

```
Get-CFGAggregationAuthorizationList
```
**輸出：**  

```
AggregationAuthorizationArn                                                            AuthorizedAccountId AuthorizedAwsRegion CreationTime
---------------------------                                                            ------------------- ------------------- ------------
arn:aws:config-service:eu-west-1:123456789012:aggregation-authorization/123456789012/eu-west-1 123456789012        eu-west-1           8/26/2019 12:55:27 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAggregationAuthorizations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGComplianceByConfigRule`
<a name="config-service_DescribeComplianceByConfigRule_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGComplianceByConfigRule`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取規則 ebs-optimized-instance 的合規詳細資訊，其中並無規則目前適用的評估結果，因此會傳回 INSUFFICIENT\$1DATA**  

```
(Get-CFGComplianceByConfigRule -ConfigRuleName ebs-optimized-instance).Compliance
```
**輸出：**  

```
ComplianceContributorCount ComplianceType
-------------------------- --------------
                           INSUFFICIENT_DATA
```
**範例 2：此範例傳回規則 ALB\$1HTTP\$1TO\$1HTTPS\$1REDIRECTION\$1CHECK 的不合規資源數目。**  

```
(Get-CFGComplianceByConfigRule -ConfigRuleName ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK -ComplianceType NON_COMPLIANT).Compliance.ComplianceContributorCount
```
**輸出：**  

```
CapExceeded CappedCount
----------- -----------
False       2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeComplianceByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGComplianceByResource`
<a name="config-service_DescribeComplianceByResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGComplianceByResource`。

**Tools for PowerShell V5**  
**範例 1：此範例會檢查 'COMPLIANT' 合規類型的 `AWS::SSM::ManagedInstanceInventory` 資源類型。**  

```
Get-CFGComplianceByResource -ComplianceType COMPLIANT -ResourceType AWS::SSM::ManagedInstanceInventory
```
**輸出：**  

```
Compliance                            ResourceId          ResourceType
----------                            ----------          ------------
Amazon.ConfigService.Model.Compliance i-0123bcf4b567890e3 AWS::SSM::ManagedInstanceInventory
Amazon.ConfigService.Model.Compliance i-0a1234f6f5d6b78f7 AWS::SSM::ManagedInstanceInventory
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeComplianceByResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGComplianceDetailsByConfigRule`
<a name="config-service_GetComplianceDetailsByConfigRule_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGComplianceDetailsByConfigRule`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得規則 access-keys-rotated 的評估結果，並傳回依 compliance-type 分組的輸出**  

```
Get-CFGComplianceDetailsByConfigRule -ConfigRuleName access-keys-rotated | Group-Object ComplianceType
```
**輸出：**  

```
Count Name                      Group
----- ----                      -----
    2 COMPLIANT                 {Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationResult}
    5 NON_COMPLIANT             {Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationRes...
```
**範例 2：此範例會查詢 COMPLIANT 資源之 access-keys-rotated 規則的合規詳細資訊。**  

```
Get-CFGComplianceDetailsByConfigRule -ConfigRuleName access-keys-rotated -ComplianceType COMPLIANT | ForEach-Object {$_.EvaluationResultIdentifier.EvaluationResultQualifier}
```
**輸出：**  

```
ConfigRuleName      ResourceId            ResourceType
--------------      ----------            ------------
access-keys-rotated BCAB1CDJ2LITAPVEW3JAH AWS::IAM::User
access-keys-rotated BCAB1CDJ2LITL3EHREM4Q AWS::IAM::User
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGComplianceDetailsByResource`
<a name="config-service_GetComplianceDetailsByResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGComplianceDetailsByResource`。

**Tools for PowerShell V5**  
**範例 1：此範例會評估給定資源的結果。**  

```
Get-CFGComplianceDetailsByResource -ResourceId ABCD5STJ4EFGHIVEW6JAH -ResourceType 'AWS::IAM::User'
```
**輸出：**  

```
Annotation                 :
ComplianceType             : COMPLIANT
ConfigRuleInvokedTime      : 8/25/2019 11:34:56 PM
EvaluationResultIdentifier : Amazon.ConfigService.Model.EvaluationResultIdentifier
ResultRecordedTime         : 8/25/2019 11:34:56 PM
ResultToken                :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetComplianceDetailsByResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGComplianceSummaryByConfigRule`
<a name="config-service_GetComplianceSummaryByConfigRule_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGComplianceSummaryByConfigRule`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回不合規的 Config 規則數目。**  

```
Get-CFGComplianceSummaryByConfigRule -Select ComplianceSummary.NonCompliantResourceCount
```
**輸出：**  

```
CapExceeded CappedCount
----------- -----------
False       9
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetComplianceSummaryByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGComplianceSummaryByResourceType`
<a name="config-service_GetComplianceSummaryByResourceType_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGComplianceSummaryByResourceType`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回合規或不合規的資源數目，並將輸出轉換為 json。**  

```
Get-CFGComplianceSummaryByResourceType -Select ComplianceSummariesByResourceType.ComplianceSummary | ConvertTo-Json
{
  "ComplianceSummaryTimestamp": "2019-12-14T06:14:49.778Z",
  "CompliantResourceCount": {
    "CapExceeded": false,
    "CappedCount": 2
  },
  "NonCompliantResourceCount": {
    "CapExceeded": true,
    "CappedCount": 100
  }
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetComplianceSummaryByResourceType](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGConfigRule`
<a name="config-service_DescribeConfigRules_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGConfigRule`。

**Tools for PowerShell V5**  
**範例 1：此範例列出具有所選屬性的帳戶 Config 規則。**  

```
Get-CFGConfigRule | Select-Object ConfigRuleName, ConfigRuleId, ConfigRuleArn, ConfigRuleState
```
**輸出：**  

```
ConfigRuleName                                    ConfigRuleId       ConfigRuleArn                                                        ConfigRuleState
--------------                                    ------------       -------------                                                        ---------------
ALB_REDIRECTION_CHECK                             config-rule-12iyn3 arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-12iyn3 ACTIVE
access-keys-rotated                               config-rule-aospfr arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-aospfr ACTIVE
autoscaling-group-elb-healthcheck-required        config-rule-cn1f2x arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-cn1f2x ACTIVE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConfigRules](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGConfigRuleEvaluationStatus`
<a name="config-service_DescribeConfigRuleEvaluationStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGConfigRuleEvaluationStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回給定 Config 規則的狀態資訊。**  

```
Get-CFGConfigRuleEvaluationStatus -ConfigRuleName root-account-mfa-enabled, vpc-flow-logs-enabled
```
**輸出：**  

```
ConfigRuleArn                : arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-kvq1wk
ConfigRuleId                 : config-rule-kvq1wk
ConfigRuleName               : root-account-mfa-enabled
FirstActivatedTime           : 8/27/2019 8:05:17 AM
FirstEvaluationStarted       : True
LastErrorCode                :
LastErrorMessage             :
LastFailedEvaluationTime     : 1/1/0001 12:00:00 AM
LastFailedInvocationTime     : 1/1/0001 12:00:00 AM
LastSuccessfulEvaluationTime : 12/13/2019 8:12:03 AM
LastSuccessfulInvocationTime : 12/13/2019 8:12:03 AM

ConfigRuleArn                : arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-z1s23b
ConfigRuleId                 : config-rule-z1s23b
ConfigRuleName               : vpc-flow-logs-enabled
FirstActivatedTime           : 8/14/2019 6:23:44 AM
FirstEvaluationStarted       : True
LastErrorCode                :
LastErrorMessage             :
LastFailedEvaluationTime     : 1/1/0001 12:00:00 AM
LastFailedInvocationTime     : 1/1/0001 12:00:00 AM
LastSuccessfulEvaluationTime : 12/13/2019 7:12:01 AM
LastSuccessfulInvocationTime : 12/13/2019 7:12:01 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConfigRuleEvaluationStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGConfigurationAggregatorList`
<a name="config-service_DescribeConfigurationAggregators_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGConfigurationAggregatorList`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回區域/帳戶的所有彙總工具。**  

```
Get-CFGConfigurationAggregatorList
```
**輸出：**  

```
AccountAggregationSources     : {Amazon.ConfigService.Model.AccountAggregationSource}
ConfigurationAggregatorArn    : arn:aws:config-service:eu-west-1:123456789012:config-aggregator/config-aggregator-xabca1me
ConfigurationAggregatorName   : IrelandMaster
CreationTime                  : 8/25/2019 11:42:39 PM
LastUpdatedTime               : 8/25/2019 11:42:39 PM
OrganizationAggregationSource :

AccountAggregationSources     : {}
ConfigurationAggregatorArn    : arn:aws:config-service:eu-west-1:123456789012:config-aggregator/config-aggregator-qubqabcd
ConfigurationAggregatorName   : raju
CreationTime                  : 8/11/2019 8:39:25 AM
LastUpdatedTime               : 8/11/2019 8:39:25 AM
OrganizationAggregationSource : Amazon.ConfigService.Model.OrganizationAggregationSource
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConfigurationAggregators](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGConfigurationAggregatorSourcesStatus`
<a name="config-service_DescribeConfigurationAggregatorSourcesStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGConfigurationAggregatorSourcesStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示給定彙總工具中來源的請求欄位。**  

```
Get-CFGConfigurationAggregatorSourcesStatus -ConfigurationAggregatorName raju | select SourceType, LastUpdateStatus, LastUpdateTime, SourceId
```
**輸出：**  

```
SourceType   LastUpdateStatus LastUpdateTime        SourceId
----------   ---------------- --------------        --------
ORGANIZATION SUCCEEDED        12/31/2019 7:45:06 AM Organization
ACCOUNT      SUCCEEDED        12/31/2019 7:09:38 AM 612641234567
ACCOUNT      SUCCEEDED        12/31/2019 7:12:53 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:18:10 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:25:17 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:25:49 AM 612641234567
ACCOUNT      SUCCEEDED        12/31/2019 7:26:11 AM 612641234567
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConfigurationAggregatorSourcesStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGConfigurationRecorder`
<a name="config-service_DescribeConfigurationRecorders_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGConfigurationRecorder`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回組態記錄器的詳細資訊。**  

```
Get-CFGConfigurationRecorder | Format-List
```
**輸出：**  

```
Name           : default
RecordingGroup : Amazon.ConfigService.Model.RecordingGroup
RoleARN        : arn:aws:iam::123456789012:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConfigurationRecorders](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGConfigurationRecorderStatus`
<a name="config-service_DescribeConfigurationRecorderStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGConfigurationRecorderStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回組態記錄器的狀態。**  

```
Get-CFGConfigurationRecorderStatus
```
**輸出：**  

```
LastErrorCode        :
LastErrorMessage     :
LastStartTime        : 10/11/2019 10:13:51 AM
LastStatus           : Success
LastStatusChangeTime : 12/31/2019 6:14:12 AM
LastStopTime         : 10/11/2019 10:13:46 AM
Name                 : default
Recording            : True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConfigurationRecorderStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGConformancePack`
<a name="config-service_DescribeConformancePacks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGConformancePack`。

**Tools for PowerShell V5**  
**範例 1：此範例列出所有一致性套件。**  

```
Get-CFGConformancePack
```
**輸出：**  

```
ConformancePackArn             : arn:aws:config:eu-west-1:123456789012:conformance-pack/dono/conformance-pack-p0acq8bpz
ConformancePackId              : conformance-pack-p0acabcde
ConformancePackInputParameters : {}
ConformancePackName            : dono
CreatedBy                      :
DeliveryS3Bucket               : kt-ps-examples
DeliveryS3KeyPrefix            :
LastUpdateRequestedTime        : 12/31/2019 8:45:31 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConformancePacks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGDeliveryChannel`
<a name="config-service_DescribeDeliveryChannels_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGDeliveryChannel`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取區域的交付管道，並顯示詳細資訊。**  

```
Get-CFGDeliveryChannel -Region eu-west-1 | Select-Object Name, S3BucketName, S3KeyPrefix, @{N="DeliveryFrequency";E={$_.ConfigSnapshotDeliveryProperties.DeliveryFrequency}}
```
**輸出：**  

```
Name    S3BucketName               S3KeyPrefix DeliveryFrequency
----    ------------               ----------- -----------------
default config-bucket-NA my          TwentyFour_Hours
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDeliveryChannels](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-CFGResourceTag`
<a name="config-service_ListTagsForResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-CFGResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例列出給定資源的相關標籤**  

```
Get-CFGResourceTag -ResourceArn $rules[0].ConfigRuleArn
```
**輸出：**  

```
Key     Value
---     -----
Version 1.3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-CFGConformancePack`
<a name="config-service_DeleteConformancePack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-CFGConformancePack`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除給定的一致性套件，以及套件的所有規則、修補動作和評估結果。**  

```
Remove-CFGConformancePack -ConformancePackName dono
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-CFGConformancePack (DeleteConformancePack)" on target "dono".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteConformancePack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-CFGConformancePack`
<a name="config-service_PutConformancePack_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-CFGConformancePack`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立一致性套件，從給定的 yaml 檔案擷取範本。**  

```
Write-CFGConformancePack -ConformancePackName dono -DeliveryS3Bucket amzn-s3-demo-bucket -TemplateBody (Get-Content C:\windows\temp\template.yaml -Raw)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutConformancePack](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-CFGDeliveryChannel`
<a name="config-service_PutDeliveryChannel_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-CFGDeliveryChannel`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更現有交付管道的 deliveryFrequency 屬性。**  

```
Write-CFGDeliveryChannel -ConfigSnapshotDeliveryProperties_DeliveryFrequency TwentyFour_Hours -DeliveryChannelName default -DeliveryChannel_S3BucketName amzn-s3-demo-bucket -DeliveryChannel_S3KeyPrefix my
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutDeliveryChannel](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Device Farm 範例
<a name="powershell_device-farm_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Device Farm 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `New-DFUpload`
<a name="device-farm_CreateUpload_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DFUpload`。

**Tools for PowerShell V5**  
**範例 1：此範例會為 Android 應用程式建立 AWS Device Farm 上傳。您可以從 New-DFProject 或 Get-DFProjectList 的輸出，取得專案 ARN。在 New-DFUpload 輸出中使用已簽署的 URL，將檔案上傳至 Device Farm。**  

```
New-DFUpload -ContentType "application/octet-stream" -ProjectArn "arn:aws:devicefarm:us-west-2:123456789012:project:EXAMPLEa-7ec1-4741-9c1f-d3e04EXAMPLE" -Name "app.apk" -Type ANDROID_APP
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateUpload](https://docs.aws.amazon.com/powershell/v5/reference)。

# Directory Service 使用 Tools for PowerShell V5 的範例
<a name="powershell_directory-service_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 Directory Service。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-DSIpRoute`
<a name="directory-service_AddIpRoutes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-DSIpRoute`。

**Tools for PowerShell V5**  
**範例 1：此命令會移除指派至指定 Directory-id 的資源標籤**  

```
Add-DSIpRoute -DirectoryId d-123456ijkl -IpRoute @{CidrIp ="203.0.113.5/32"} -UpdateSecurityGroupForDirectoryController $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-DSResourceTag`
<a name="directory-service_AddTagsToResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-DSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此命令會將資源標籤新增至指定的 Directory-id**  

```
Add-DSResourceTag -ResourceId d-123456ijkl -Tag @{Key="myTag"; Value="mytgValue"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddTagsToResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Approve-DSTrust`
<a name="directory-service_VerifyTrust_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Approve-DSTrust`。

**Tools for PowerShell V5**  
**範例 1：此範例會呼叫指定 Trustid 的 AWS Directory Service VerifyTrust API 操作。**  

```
Approve-DSTrust -TrustId t-9067157123
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [VerifyTrust](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Confirm-DSSharedDirectory`
<a name="directory-service_AcceptSharedDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Confirm-DSSharedDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例接受從目錄擁有者傳送的目錄共用請求 AWS 帳戶。**  

```
Confirm-DSSharedDirectory -SharedDirectoryId d-9067012345
```
**輸出：**  

```
CreatedDateTime     : 12/30/2019 4:20:27 AM
LastUpdatedDateTime : 12/30/2019 4:21:40 AM
OwnerAccountId      : 123456781234
OwnerDirectoryId    : d-123456ijkl
SharedAccountId     : 123456784321
SharedDirectoryId   : d-9067012345
ShareMethod         :
ShareNotes          : This is test sharing
ShareStatus         : Sharing
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AcceptSharedDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Connect-DSDirectory`
<a name="directory-service_ConnectDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Connect-DSDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立 AD Connector，以連接到內部部署目錄。**  

```
Connect-DSDirectory -Name contoso.com -ConnectSettings_CustomerUserName Administrator -Password $Password -ConnectSettings_CustomerDnsIp 172.31.36.96 -ShortName CONTOSO -Size Small -ConnectSettings_VpcId vpc-123459da -ConnectSettings_SubnetId subnet-1234ccaa, subnet-5678ffbb
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ConnectDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Deny-DSSharedDirectory`
<a name="directory-service_RejectSharedDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Deny-DSSharedDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例拒絕從目錄擁有者傳送的目錄共用請求。**  

```
Deny-DSSharedDirectory -SharedDirectoryId d-9067012345
```
**輸出：**  

```
d-9067012345
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RejectSharedDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-DSDirectoryShare`
<a name="directory-service_UnshareDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-DSDirectoryShare`。

**Tools for PowerShell V5**  
**範例 1：此範例會停止目錄擁有者與取用者帳戶之間的目錄共用。**  

```
Disable-DSDirectoryShare -DirectoryId d-123456ijkl -UnshareTarget_Id 123456784321 -UnshareTarget_Type ACCOUNT
```
**輸出：**  

```
d-9067012345
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UnshareDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-DSLDAPS`
<a name="directory-service_DisableLDAPS_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-DSLDAPS`。

**Tools for PowerShell V5**  
**範例 1：此範例會停用指定目錄的 LDAP 安全呼叫。**  

```
Disable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableLDAPS](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-DSRadius`
<a name="directory-service_DisableRadius_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-DSRadius`。

**Tools for PowerShell V5**  
**範例 1：此範例會停用針對 AD Connector 或 Microsoft AD 目錄設定的 RADIUS 伺服器。**  

```
Disable-DSRadius -DirectoryId d-123456ijkl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableRadius](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-DSSso`
<a name="directory-service_DisableSso_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-DSSso`。

**Tools for PowerShell V5**  
**範例 1：此範例會停用目錄的單一登入。**  

```
Disable-DSSso -DirectoryId d-123456ijkl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableSso](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-DSDirectoryShare`
<a name="directory-service_ShareDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-DSDirectoryShare`。

**Tools for PowerShell V5**  
**範例 1：此範例使用交握方法與另一個 AWS 帳戶共用您 AWS 帳戶中指定的目錄。 **  

```
Enable-DSDirectoryShare -DirectoryId d-123456ijkl -ShareTarget_Id 123456784321 -ShareMethod HANDSHAKE -ShareTarget_Type ACCOUNT
```
**輸出：**  

```
d-9067012345
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ShareDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-DSLDAPS`
<a name="directory-service_EnableLDAPS_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-DSLDAPS`。

**Tools for PowerShell V5**  
**範例 1：此範例啟用特定目錄的切換開關，以永遠使用 LDAP 安全呼叫。**  

```
Enable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**的 [EnableLDAPS](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-DSRadius`
<a name="directory-service_EnableRadius_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-DSRadius`。

**Tools for PowerShell V5**  
**範例 1：此範例利用 AD Connector 或 Microsoft AD 目錄的 RADIUS 伺服器組態，啟用多重要素驗證 (MFA)。**  

```
Enable-DSRadius -DirectoryId d-123456ijkl 
-RadiusSettings_AuthenticationProtocol PAP 
-RadiusSettings_DisplayLabel Radius 
-RadiusSettings_RadiusPort 1812 
-RadiusSettings_RadiusRetry 4 
-RadiusSettings_RadiusServer 10.4.185.113 
-RadiusSettings_RadiusTimeout 50 
-RadiusSettings_SharedSecret wJalrXUtnFEMI
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableRadius](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-DSSso`
<a name="directory-service_EnableSso_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-DSSso`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用目錄的單一登入。**  

```
Enable-DSSso -DirectoryId d-123456ijkl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableSso](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSCertificate`
<a name="directory-service_DescribeCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示為安全 LDAP 連線註冊的憑證相關資訊。**  

```
Get-DSCertificate -DirectoryId d-123456ijkl -CertificateId c-906731e34f
```
**輸出：**  

```
CertificateId      : c-906731e34f
CommonName         : contoso-EC2AMAZ-CTGG2NM-CA
ExpiryDateTime     : 4/15/2025 6:34:15 PM
RegisteredDateTime : 4/15/2020 6:38:56 PM
State              : Registered
StateReason        : Certificate registered successfully.
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSCertificateList`
<a name="directory-service_ListCertificates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSCertificateList`。

**Tools for PowerShell V5**  
範例 1：此範例針對指定的目錄，列出已註冊為安全 LDAP 連線的所有憑證。****  

```
Get-DSCertificateList -DirectoryId d-123456ijkl
```
**輸出：**  

```
CertificateId CommonName                 ExpiryDateTime       State
------------- ----------                 --------------       -----
c-906731e34f  contoso-EC2AMAZ-CTGG2NM-CA 4/15/2025 6:34:15 PM Registered
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListCertificates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSConditionalForwarder`
<a name="directory-service_DescribeConditionalForwarders_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSConditionalForwarder`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得給定 Directory-id 的所有設定的條件式轉寄站。**  

```
Get-DSConditionalForwarder -DirectoryId d-123456ijkl
```
**輸出：**  

```
DnsIpAddrs      RemoteDomainName ReplicationScope
----------      ---------------- ----------------
{172.31.77.239} contoso.com      Domain
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeConditionalForwarders](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSDirectory`
<a name="directory-service_DescribeDirectories_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSDirectory`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得屬於此帳戶的目錄的相關資訊。**  

```
Get-DSDirectory | Select-Object DirectoryId, Name, DnsIpAddrs, Type
```
**輸出：**  

```
DirectoryId  Name           DnsIpAddrs                     Type
-----------  ----           ----------                     ----
d-123456abcd abcd.example.com {172.31.74.189, 172.31.13.145} SimpleAD
d-123456efgh wifi.example.com {172.31.16.108, 172.31.10.56}  ADConnector
d-123456ijkl lan2.example.com {172.31.10.56, 172.31.16.108}  MicrosoftAD
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDirectories](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSDirectoryLimit`
<a name="directory-service_GetDirectoryLimits_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSDirectoryLimit`。

**Tools for PowerShell V5**  
**範例 1：此範例會顯示 us-east-1 區域的目錄限制資訊。**  

```
Get-DSDirectoryLimit -Region us-east-1
```
**輸出：**  

```
CloudOnlyDirectoriesCurrentCount : 1
CloudOnlyDirectoriesLimit        : 10
CloudOnlyDirectoriesLimitReached : False
CloudOnlyMicrosoftADCurrentCount : 1
CloudOnlyMicrosoftADLimit        : 20
CloudOnlyMicrosoftADLimitReached : False
ConnectedDirectoriesCurrentCount : 1
ConnectedDirectoriesLimit        : 10
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDirectoryLimits](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSDomainControllerList`
<a name="directory-service_DescribeDomainControllers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSDomainControllerList`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得針對提及的 directory-id 啟動的網域控制站詳細清單**  

```
Get-DSDomainControllerList -DirectoryId d-123456ijkl
```
**輸出：**  

```
AvailabilityZone          : us-east-1b
DirectoryId               : d-123456ijkl
DnsIpAddr                 : 172.31.16.108
DomainControllerId        : dc-1234567aa6
LaunchTime                : 4/4/2019 4:53:43 AM
Status                    : Active
StatusLastUpdatedDateTime : 4/24/2019 1:37:54 PM
StatusReason              :
SubnetId                  : subnet-1234kkaa
VpcId                     : vpc-123459d

AvailabilityZone          : us-east-1d
DirectoryId               : d-123456ijkl
DnsIpAddr                 : 172.31.10.56
DomainControllerId        : dc-1234567aa7
LaunchTime                : 4/4/2019 4:53:43 AM
Status                    : Active
StatusLastUpdatedDateTime : 4/4/2019 5:14:31 AM
StatusReason              :
SubnetId                  : subnet-5678ffbb
VpcId                     : vpc-123459d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDomainControllers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSEventTopic`
<a name="directory-service_DescribeEventTopics_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSEventTopic`。

**Tools for PowerShell V5**  
**範例 1：此命令顯示目錄狀態變更時所設定 SNS 主題的通知資訊。**  

```
Get-DSEventTopic -DirectoryId d-123456ijkl
```
**輸出：**  

```
CreatedDateTime : 12/13/2019 11:15:32 AM
DirectoryId     : d-123456ijkl
Status          : Registered
TopicArn        : arn:aws:sns:us-east-1:123456781234:snstopicname
TopicName       : snstopicname
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEventTopics](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSIpRouteList`
<a name="directory-service_ListIpRoutes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSIpRouteList`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得在目錄 IP 路由中設定的公有 IP 位址區塊**  

```
Get-DSIpRouteList -DirectoryId d-123456ijkl
```
**輸出：**  

```
AddedDateTime       : 12/13/2019 12:27:22 PM
CidrIp              : 203.0.113.5/32
Description         : Public IP of On-Prem DNS Server
DirectoryId         : d-123456ijkl
IpRouteStatusMsg    : Added
IpRouteStatusReason :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSLDAPSSetting`
<a name="directory-service_DescribeLDAPSSettings_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSLDAPSSetting`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定目錄的 LDAP 安全狀態。**  

```
Get-DSLDAPSSetting -DirectoryId d-123456ijkl
```
**輸出：**  

```
LastUpdatedDateTime  LDAPSStatus LDAPSStatusReason
-------------------  ----------- -----------------
4/15/2020 6:51:03 PM Enabled     LDAPS is enabled successfully.
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLDAPSSettings](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSLogSubscriptionList`
<a name="directory-service_ListLogSubscriptions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSLogSubscriptionList`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得指定 directory-id 的日誌訂閱資訊**  

```
Get-DSLogSubscriptionList -DirectoryId d-123456ijkl
```
**輸出：**  

```
DirectoryId  LogGroupName                                        SubscriptionCreatedDateTime
-----------  ------------                                        ---------------------------
d-123456ijkl /aws/directoryservice/d-123456ijkl-lan2.example.com 12/14/2019 9:05:23 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListLogSubscriptions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSResourceTag`
<a name="directory-service_ListTagsForResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得指定目錄的所有標籤。**  

```
Get-DSResourceTag -ResourceId d-123456ijkl
```
**輸出：**  

```
Key   Value
---   -----
myTag myTagValue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSSchemaExtension`
<a name="directory-service_ListSchemaExtensions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSSchemaExtension`。

**Tools for PowerShell V5**  
**範例 1：此範例列出套用到 Microsoft AD 目錄的所有結構描述延伸。**  

```
Get-DSSchemaExtension -DirectoryId d-123456ijkl
```
**輸出：**  

```
Description                 : ManagedADSchemaExtension
DirectoryId                 : d-123456ijkl
EndDateTime                 : 4/12/2020 10:30:49 AM
SchemaExtensionId           : e-9067306643
SchemaExtensionStatus       : Completed
SchemaExtensionStatusReason : Schema updates are complete.
StartDateTime               : 4/12/2020 10:28:42 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListSchemaExtensions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSSharedDirectory`
<a name="directory-service_DescribeSharedDirectories_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSSharedDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得您 AWS 帳戶的共用目錄**  

```
Get-DSSharedDirectory -OwnerDirectoryId d-123456ijkl -SharedDirectoryId d-9067012345
```
**輸出：**  

```
CreatedDateTime     : 12/30/2019 4:34:37 AM
LastUpdatedDateTime : 12/30/2019 4:35:22 AM
OwnerAccountId      : 123456781234
OwnerDirectoryId    : d-123456ijkl
SharedAccountId     : 123456784321
SharedDirectoryId   : d-9067012345
ShareMethod         : HANDSHAKE
ShareNotes          : This is a test Sharing
ShareStatus         : Shared
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSharedDirectories](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSSnapshot`
<a name="directory-service_DescribeSnapshots_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSSnapshot`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得屬於此帳戶之指定目錄快照的相關資訊。**  

```
Get-DSSnapshot -DirectoryId d-123456ijkl
```
**輸出：**  

```
DirectoryId : d-123456ijkl
Name        :
SnapshotId  : s-9064bd1234
StartTime   : 12/13/2019 6:33:01 PM
Status      : Completed
Type        : Auto

DirectoryId : d-123456ijkl
Name        :
SnapshotId  : s-9064bb4321
StartTime   : 12/9/2019 9:48:11 PM
Status      : Completed
Type        : Auto
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSSnapshotLimit`
<a name="directory-service_GetSnapshotLimits_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSSnapshotLimit`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得指定目錄的手動快照限制。**  

```
Get-DSSnapshotLimit -DirectoryId d-123456ijkl
```
**輸出：**  

```
ManualSnapshotsCurrentCount ManualSnapshotsLimit ManualSnapshotsLimitReached
--------------------------- -------------------- ---------------------------
0                           5                    False
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetSnapshotLimits](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSTrust`
<a name="directory-service_DescribeTrusts_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DSTrust`。

**Tools for PowerShell V5**  
**範例 1：此命令會取得為指定之 directory-id 建立的信任關係資訊。**  

```
Get-DSTrust -DirectoryId d-123456abcd
```
**輸出：**  

```
CreatedDateTime          : 7/5/2019 4:55:42 AM
DirectoryId              : d-123456abcd
LastUpdatedDateTime      : 7/5/2019 4:56:04 AM
RemoteDomainName         : contoso.com
SelectiveAuth            : Disabled
StateLastUpdatedDateTime : 7/5/2019 4:56:04 AM
TrustDirection           : One-Way: Incoming
TrustId                  : t-9067157123
TrustState               : Created
TrustStateReason         :
TrustType                : Forest
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTrusts](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSAlias`
<a name="directory-service_CreateAlias_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSAlias`。

**Tools for PowerShell V5**  
**範例 1：此命令會建立目錄的別名，並將別名指派給指定的 directory-id。**  

```
New-DSAlias -DirectoryId d-123456ijkl -Alias MyOrgName
```
**輸出：**  

```
Alias     DirectoryId
-----     -----------
myorgname d-123456ijkl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAlias](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSComputer`
<a name="directory-service_CreateComputer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSComputer`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的 Active Directory 電腦物件。**  

```
New-DSComputer -DirectoryId d-123456ijkl -ComputerName ADMemberServer -Password $Password
```
**輸出：**  

```
ComputerAttributes                  ComputerId                                    ComputerName
------------------                  ----------                                    ------------
{WindowsSamName, DistinguishedName} S-1-5-21-1191241402-978882507-2717148213-1662 ADMemberServer
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateComputer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSConditionalForwarder`
<a name="directory-service_CreateConditionalForwarder_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSConditionalForwarder`。

**Tools for PowerShell V5**  
**範例 1：此範例會在指定的 AWS Directory-id 中建立條件式轉送器。 **  

```
New-DSConditionalForwarder -DirectoryId d-123456ijkl -DnsIpAddr 172.31.36.96,172.31.10.56 -RemoteDomainName contoso.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSDirectory`
<a name="directory-service_CreateDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的 Simple AD 目錄。**  

```
New-DSDirectory -Name corp.example.com -Password $Password -Size Small -VpcSettings_VpcId vpc-123459d -VpcSettings_SubnetIds subnet-1234kkaa,subnet-5678ffbb
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSLogSubscription`
<a name="directory-service_CreateLogSubscription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSLogSubscription`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立訂閱，將即時 Directory Service 網域控制器安全日誌轉送到您 AWS 帳戶中指定的 Amazon CloudWatch 日誌群組。**  

```
New-DSLogSubscription -DirectoryId d-123456ijkl -LogGroupName /aws/directoryservice/d-123456ijkl-lan2.example.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLogSubscription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSMicrosoftAD`
<a name="directory-service_CreateMicrosoftAD_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSMicrosoftAD`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 中建立新的 Microsoft AD Directory AWS 雲端。**  

```
New-DSMicrosoftAD -Name corp.example.com -Password $Password -edition Standard -VpcSettings_VpcId vpc-123459d -VpcSettings_SubnetIds subnet-1234kkaa,subnet-5678ffbb
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateMicrosoftAD](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSSnapshot`
<a name="directory-service_CreateSnapshot_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSSnapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立目錄快照**  

```
New-DSSnapshot -DirectoryId d-123456ijkl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSTrust`
<a name="directory-service_CreateTrust_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DSTrust`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 AWS Managed Microsoft AD 目錄與現有的內部部署 Microsoft Active Directory 之間建立雙向全森林信任。**  

```
New-DSTrust -DirectoryId d-123456ijkl -RemoteDomainName contoso.com -TrustDirection Two-Way -TrustType Forest -TrustPassword $Password -ConditionalForwarderIpAddr 172.31.36.96
```
**輸出：**  

```
t-9067157123
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateTrust](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-DSCertificate`
<a name="directory-service_RegisterCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-DSCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例為註冊安全 LDAP 連線的憑證。**  

```
$Certificate = Get-Content contoso.cer -Raw
Register-DSCertificate -DirectoryId d-123456ijkl -CertificateData $Certificate
```
**輸出：**  

```
c-906731e350
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-DSEventTopic`
<a name="directory-service_RegisterEventTopic_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-DSEventTopic`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立用作發布者的目錄，與 SNS 主題的關聯。**  

```
Register-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterEventTopic](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DSConditionalForwarder`
<a name="directory-service_DeleteConditionalForwarder_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DSConditionalForwarder`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除已針對 AWS 您的分類設定的條件式轉送器。**  

```
Remove-DSConditionalForwarder -DirectoryId d-123456ijkl -RemoteDomainName contoso.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DSDirectory`
<a name="directory-service_DeleteDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DSDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 AWS Directory 服務目錄 (Simple AD/Microsoft AD/AD Connector)**  

```
Remove-DSDirectory -DirectoryId d-123456ijkl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DSIpRoute`
<a name="directory-service_RemoveIpRoutes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DSIpRoute`。

**Tools for PowerShell V5**  
**範例 1：此命令會從 Directory-id 的已設定 IP 路由中，移除指定的 IP。**  

```
Remove-DSIpRoute -DirectoryId d-123456ijkl -CidrIp 203.0.113.5/32
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DSLogSubscription`
<a name="directory-service_DeleteLogSubscription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DSLogSubscription`。

**Tools for PowerShell V5**  
**範例 1：此命令會移除指定之 Directory-id 的日誌訂閱**  

```
Remove-DSLogSubscription -DirectoryId d-123456ijkl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLogSubscription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DSResourceTag`
<a name="directory-service_RemoveTagsFromResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此命令會移除指派至指定 Directory-id 的資源標籤**  

```
Remove-DSResourceTag -ResourceId d-123456ijkl -TagKey myTag
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DSSnapshot`
<a name="directory-service_DeleteSnapshot_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DSSnapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除手動建立的快照。**  

```
Remove-DSSnapshot -SnapshotId s-9068b488kc
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DSTrust`
<a name="directory-service_DeleteTrust_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DSTrust`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除 AWS Managed AD Directory 與外部網域之間存在的信任關係。**  

```
Get-DSTrust -DirectoryId d-123456ijkl -Select Trusts.TrustId | Remove-DSTrust
```
**輸出：**  

```
t-9067157123
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteTrust](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Reset-DSUserPassword`
<a name="directory-service_ResetUserPassword_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Reset-DSUserPassword`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 AWS Managed microsoft AD 或 Simple AD Directory 中重設名為 ADUser 的 Active Direcotry 使用者密碼**  

```
Reset-DSUserPassword -UserName ADuser -DirectoryId d-123456ijkl -NewPassword $Password
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResetUserPassword](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Restore-DSFromSnapshot`
<a name="directory-service_RestoreFromSnapshot_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Restore-DSFromSnapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例使用現有的目錄快照還原目錄。**  

```
Restore-DSFromSnapshot -SnapshotId s-9068b488kc
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RestoreFromSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-DSDomainControllerCount`
<a name="directory-service_UpdateNumberOfDomainControllers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-DSDomainControllerCount`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定之 directory-id 的網域控制站數目設定為 3。**  

```
Set-DSDomainControllerCount -DirectoryId d-123456ijkl -DesiredNumber 3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateNumberOfDomainControllers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-DSSchemaExtension`
<a name="directory-service_StartSchemaExtension_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-DSSchemaExtension`。

**Tools for PowerShell V5**  
**範例 1：此範例會將結構描述延伸，套用至 Microsoft AD 目錄。**  

```
$ldif = Get-Content D:\Users\Username\Downloads\ExtendedSchema.ldf -Raw
Start-DSSchemaExtension -DirectoryId d-123456ijkl -CreateSnapshotBeforeSchemaExtension $true -Description ManagedADSchemaExtension -LdifContent $ldif
```
**輸出：**  

```
e-9067306643
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartSchemaExtension](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-DSSchemaExtension`
<a name="directory-service_CancelSchemaExtension_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-DSSchemaExtension`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消 Microsoft AD 目錄的進行中結構描述延伸。**  

```
Stop-DSSchemaExtension -DirectoryId d-123456ijkl -SchemaExtensionId e-9067306643
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelSchemaExtension](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-DSCertificate`
<a name="directory-service_DeregisterCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-DSCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會將從系統刪除已註冊安全 LDAP 連線的憑證。**  

```
Unregister-DSCertificate -DirectoryId d-123456ijkl -CertificateId c-906731e34f
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-DSEventTopic`
<a name="directory-service_DeregisterEventTopic_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-DSEventTopic`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除用作指定之 SNS 主題發布者的指定目錄。**  

```
Unregister-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterEventTopic](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-DSConditionalForwarder`
<a name="directory-service_UpdateConditionalForwarder_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-DSConditionalForwarder`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新已為您的 AWS 目錄設定的條件式轉送器。**  

```
Update-DSConditionalForwarder -DirectoryId d-123456ijkl -DnsIpAddr 172.31.36.96,172.31.16.108 -RemoteDomainName contoso.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-DSRadius`
<a name="directory-service_UpdateRadius_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-DSRadius`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新 AD Connector 或 Microsoft AD 目錄的 RADIUS 伺服器資訊。**  

```
Update-DSRadius -DirectoryId d-123456ijkl -RadiusSettings_RadiusRetry 3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateRadius](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-DSTrust`
<a name="directory-service_UpdateTrust_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-DSTrust`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定 trust-id 的 SelectiveAuth 參數，從「已停用」更新為「已啟用」。**  

```
Update-DSTrust -TrustId t-9067157123 -SelectiveAuth Enabled
```
**輸出：**  

```
RequestId                            TrustId
---------                            -------
138864a7-c9a8-4ad1-a828-eae479e85b45 t-9067157123
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateTrust](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS DMS 使用 Tools for PowerShell V5 的範例
<a name="powershell_database-migration-service_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS DMS。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `New-DMSReplicationTask`
<a name="database-migration-service_CreateReplicationTask_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DMSReplicationTask`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的 AWS Database Migration Service 複寫任務，使用 CdcStartTime 而非 CdcStartPosition。MigrationType 設定為 "full-load-and-cdc"，意思是目標資料表必須為空白。新任務會加上具有 Stage 索引鍵和 Test 鍵值的標籤。如需此 cmdlet 所用值的詳細資訊，請參閱《 AWS Database Migration Service 使用者指南》中的建立任務 (https：//https://docs.aws.amazon.com/dms/latest/userguide/CHAP\$1Tasks.Creating.html)。**  

```
New-DMSReplicationTask -ReplicationInstanceArn "arn:aws:dms:us-east-1:123456789012:rep:EXAMPLE66XFJUWATDJGBEXAMPLE"`
  -CdcStartTime "2019-08-08T12:12:12"`
  -CdcStopPosition "server_time:2019-08-09T12:12:12"`
  -MigrationType "full-load-and-cdc"`
  -ReplicationTaskIdentifier "task1"`
  -ReplicationTaskSetting ""`
  -SourceEndpointArn "arn:aws:dms:us-east-1:123456789012:endpoint:EXAMPLEW5UANC7Y3P4EEXAMPLE"`
  -TableMapping "file:////home/testuser/table-mappings.json"`
  -Tag @{"Key"="Stage";"Value"="Test"}`
  -TargetEndpointArn "arn:aws:dms:us-east-1:123456789012:endpoint:EXAMPLEJZASXWHTWCLNEXAMPLE"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateReplicationTask](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 DynamoDB 範例
<a name="powershell_dynamodb_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 DynamoDB 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-DDBIndexSchema`
<a name="dynamodb_Add-DDBIndexSchema_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-DDBIndexSchema`。

**Tools for PowerShell V5**  
**範例 1：建立空的 TableSchema 物件，並在將 TableSchema 物件寫入管道之前，為其新增本機次要索引定義。**  

```
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema = New-DDBTableSchema
```
**輸出：**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{LastPostDateTime}                          {}                                          {LastPostIndex}
```
**範例 2：將新的本機次要索引定義新增至提供的 TableSchema 物件，然後再將 TableSchema 物件寫入管道。也可以使用 -Schema 參數提供 TableSchema 物件。**  

```
New-DDBTableSchema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
```
**輸出：**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{LastPostDateTime}                          {}                                          {LastPostIndex}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Add-DDBIndexSchema](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-DDBKeySchema`
<a name="dynamodb_Add-DDBKeySchema_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-DDBKeySchema`。

**Tools for PowerShell V5**  
**範例 1：建立空的 TableSchema 物件，並使用指定的索引鍵資料，將索引鍵和屬性定義項目新增至其中，然後才能將 TableSchema 物件寫入管道。根據預設，索引鍵類型宣告為 'HASH'；使用值為 'RANGE' 的 -KeyType paameter 宣告範圍索引鍵。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**輸出：**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
**範例 2：在將 TableSchema 物件寫入管道之前，將新的索引鍵和屬性定義項目新增至提供的 TableSchema 物件。根據預設，索引鍵類型宣告為 'HASH'；使用值為 'RANGE' 的 -KeyType paameter 宣告範圍索引鍵。也可以使用 -Schema 參數提供 TableSchema 物件。**  

```
New-DDBTableSchema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**輸出：**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Add-DDBKeySchema](https://docs.aws.amazon.com/powershell/v5/reference)。

### `ConvertFrom-DDBItem`
<a name="dynamodb_ConvertFrom-DDBItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `ConvertFrom-DDBItem`。

**Tools for PowerShell V5**  
**範例 1：ConvertFrom-DDBItem 用於將 Get-DDBItem 的結果，從 DynamoDB AttributeValues 的雜湊表轉換為字串和雙精度等常見類型的雜湊表。**  

```
@{
    SongTitle = 'Somewhere Down The Road'
    Artist    = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**輸出：**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ConvertFrom-DDBItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `ConvertTo-DDBItem`
<a name="dynamodb_ConvertTo-DDBItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `ConvertTo-DDBItem`。

**Tools for PowerShell V5**  
**範例 1：將雜湊表轉換為 DynamoDB 屬性值的字典範例。**  

```
@{
    SongTitle = 'Somewhere Down The Road'
    Artist    = 'No One You Know'
} | ConvertTo-DDBItem

Key       Value
---       -----
SongTitle Amazon.DynamoDBv2.Model.AttributeValue
Artist    Amazon.DynamoDBv2.Model.AttributeValue
```
**範例 2：將雜湊表轉換為 DynamoDB 屬性值的字典範例。**  

```
@{
    MyMap        = @{
        MyString = 'my string'
    }
    MyStringSet  = [System.Collections.Generic.HashSet[String]]@('my', 'string')
    MyNumericSet = [System.Collections.Generic.HashSet[Int]]@(1, 2, 3)
    MyBinarySet  = [System.Collections.Generic.HashSet[System.IO.MemoryStream]]@(
        ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes('my'))),
        ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes('string')))
    )
    MyList1      = @('my', 'string')
    MyList2      = [System.Collections.Generic.List[Int]]@(1, 2)
    MyList3      = [System.Collections.ArrayList]@('one', 2, $true)
} | ConvertTo-DDBItem
```
**輸出：**  

```
Key          Value
---          -----
MyStringSet  Amazon.DynamoDBv2.Model.AttributeValue
MyList1      Amazon.DynamoDBv2.Model.AttributeValue
MyNumericSet Amazon.DynamoDBv2.Model.AttributeValue
MyList2      Amazon.DynamoDBv2.Model.AttributeValue
MyBinarySet  Amazon.DynamoDBv2.Model.AttributeValue
MyMap        Amazon.DynamoDBv2.Model.AttributeValue
MyList3      Amazon.DynamoDBv2.Model.AttributeValue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ConvertTo-DDBItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DDBBatchItem`
<a name="dynamodb_BatchGetItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DDBBatchItem`。

**Tools for PowerShell V5**  
**範例 1：從 DynamoDB 資料表 'Music' 和 'Songs' 取得具有 SongTitle "Somewhere Down The Road" 的項目。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem

$keysAndAttributes = New-Object Amazon.DynamoDBv2.Model.KeysAndAttributes
$list = New-Object 'System.Collections.Generic.List[System.Collections.Generic.Dictionary[String, Amazon.DynamoDBv2.Model.AttributeValue]]'
$list.Add($key)
$keysAndAttributes.Keys = $list

$requestItem = @{
    'Music' = [Amazon.DynamoDBv2.Model.KeysAndAttributes]$keysAndAttributes
    'Songs' = [Amazon.DynamoDBv2.Model.KeysAndAttributes]$keysAndAttributes
}

$batchItems = Get-DDBBatchItem -RequestItem $requestItem
$batchItems.GetEnumerator() | ForEach-Object {$PSItem.Value} | ConvertFrom-DDBItem
```
**輸出：**  

```
Name                           Value
----                           -----
Artist                         No One You Know
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
CriticRating                   10
Genre                          Country
Price                          1.94
Artist                         No One You Know
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
CriticRating                   10
Genre                          Country
Price                          1.94
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchGetItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DDBItem`
<a name="dynamodb_GetItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DDBItem`。

**Tools for PowerShell V5**  
**範例 1：使用分割區索引鍵 SongTitle 和排序索引鍵 Artist 傳回 DynamoDB 項目。**  

```
$key = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**輸出：**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DDBTable`
<a name="dynamodb_DescribeTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DDBTable`。

**Tools for PowerShell V5**  
**範例 1：傳回指定資料表的詳細資訊。**  

```
Get-DDBTable -TableName "myTable"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTable](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DDBTableList`
<a name="dynamodb_ListTables_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-DDBTableList`。

**Tools for PowerShell V5**  
**範例 1：傳回所有資料表的詳細資訊，自動迭代，直到服務指出不存在其他資料表為止。**  

```
Get-DDBTableList
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTables](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Invoke-DDBQuery`
<a name="dynamodb_Query_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Invoke-DDBQuery`。

**Tools for PowerShell V5**  
**範例 1：調用查詢，傳回具有指定之 SongTitle 和 Artist 的 DynamoDB 項目。**  

```
$invokeDDBQuery = @{
    TableName = 'Music'
    KeyConditionExpression = ' SongTitle = :SongTitle and Artist = :Artist'
    ExpressionAttributeValues = @{
        ':SongTitle' = 'Somewhere Down The Road'
        ':Artist' = 'No One You Know'
    } | ConvertTo-DDBItem
}
Invoke-DDBQuery @invokeDDBQuery | ConvertFrom-DDBItem
```
**輸出：**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Query](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Invoke-DDBScan`
<a name="dynamodb_Scan_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Invoke-DDBScan`。

**Tools for PowerShell V5**  
**範例 1：傳回 Music 資料表中的所有項目。**  

```
Invoke-DDBScan -TableName 'Music' | ConvertFrom-DDBItem
```
**輸出：**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
Genre                          Country
Artist                         No One You Know
Price                          1.98
CriticRating                   8.4
SongTitle                      My Dog Spot
AlbumTitle                     Hey Now
```
**範例 2：傳回 Music 資料表中 CriticRating 大於或等於九的項目。**  

```
$scanFilter = @{
        CriticRating = [Amazon.DynamoDBv2.Model.Condition]@{
            AttributeValueList = @(@{N = '9'})
            ComparisonOperator = 'GE'
        }
    }
    Invoke-DDBScan -TableName 'Music' -ScanFilter $scanFilter | ConvertFrom-DDBItem
```
**輸出：**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Scan](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DDBTable`
<a name="dynamodb_CreateTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DDBTable`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 Thread 的資料表，其主索引鍵包含 'ForumName' (索引鍵類型雜湊) 和 'Subject' (索引鍵類型範圍)。用來建構資料表的結構描述，可以使用 -Schema 參數，依照所示或指定方式輸送至每個 cmdlet。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyType RANGE -KeyDataType "S"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**輸出：**  

```
AttributeDefinitions   : {ForumName, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {}
```
**範例 2：此範例會建立名為 Thread 的資料表，其主索引鍵包含 'ForumName' (索引鍵類型雜湊) 和 'Subject' (索引鍵類型範圍)。也會定義本機次要索引。本機次要索引的索引鍵會從資料表 (ForumName) 上的主要雜湊索引鍵自動設定。用來建構資料表的結構描述，可以使用 -Schema 參數，依照所示或指定方式輸送至每個 cmdlet。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S"
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**輸出：**  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
**範例 3：此範例示範如何使用單一管道建立名為 Thread 的資料表，該資料表的主索引鍵包含 'ForumName' (索引鍵類型雜湊) 和 'Subject' (索引鍵類型範圍) 以及本機次要索引。如果管道或 -Schema 參數未提供新的 TableSchema 物件，Add-DDBKeySchema 和 Add-DDBIndexSchema 會為您建立新的 TableSchema 物件。**  

```
New-DDBTableSchema |
  Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S" |
  Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S" |
  Add-DDBIndexSchema -IndexName "LastPostIndex" `
                     -RangeKeyName "LastPostDateTime" `
                     -RangeKeyDataType "S" `
                     -ProjectionType "keys_only" |
  New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**輸出：**  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
+  如需 API 詳細資訊，請參閱*《AWS Tools for PowerShell Cmdlet 參考 (V5)》*中的 [CreateTable](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DDBTableSchema`
<a name="dynamodb_New-DDBTableSchema_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-DDBTableSchema`。

**Tools for PowerShell V5**  
**範例 1：建立空 TableSchema 物件，準備好接受鍵和索引定義，以用於建立新的 Amazon DynamoDB 資料表。傳回的物件可以透過管道傳輸到 Add-DDBKeySchema、Add-DDBIndexSchema 和 New-DDBTable Cmdlet，或使用每個 Cmdlet 上的 -Schema 參數傳遞給它們。**  

```
New-DDBTableSchema
```
**輸出：**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{}                                          {}                                          {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [New-DDBTableSchema](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DDBItem`
<a name="dynamodb_DeleteItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DDBItem`。

**Tools for PowerShell V5**  
**範例 1：移除符合所提供索引鍵的 DynamoDB 項目。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem
Remove-DDBItem -TableName 'Music' -Key $key -Confirm:$false
```
+  如需 API 詳細資訊，請參閱AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-DDBTable`
<a name="dynamodb_DeleteTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-DDBTable`。

**Tools for PowerShell V5**  
**範例 1：刪除指定的資料表。在繼續操作之前，系統會提示您確認。**  

```
Remove-DDBTable -TableName "myTable"
```
**範例 2：刪除指定的資料表。在繼續操作之前，系統不會提示您進行確認。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  如需 API 詳細資訊，請參閱*《AWS Tools for PowerShell Cmdlet 參考 (V5)》*中的 [DeleteTable](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-DDBBatchItem`
<a name="dynamodb_BatchWriteItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-DDBBatchItem`。

**Tools for PowerShell V5**  
**範例 1：建立新的項目，或將現有項目取代為 DynamoDB 資料表 Music 和 Songs 中的新項目。**  

```
$item = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
    AlbumTitle = 'Somewhat Famous'
    Price = 1.94
    Genre = 'Country'
    CriticRating = 10.0
} | ConvertTo-DDBItem

$writeRequest = New-Object Amazon.DynamoDBv2.Model.WriteRequest
$writeRequest.PutRequest = [Amazon.DynamoDBv2.Model.PutRequest]$item

$requestItem = @{
    'Music' = [Amazon.DynamoDBv2.Model.WriteRequest]($writeRequest)
    'Songs' = [Amazon.DynamoDBv2.Model.WriteRequest]($writeRequest)
}

Set-DDBBatchItem -RequestItem $requestItem
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [BatchWriteItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-DDBItem`
<a name="dynamodb_PutItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-DDBItem`。

**Tools for PowerShell V5**  
**範例 1：建立新的項目，或將現有項目取代為新項目。**  

```
$item = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
        AlbumTitle = 'Somewhat Famous'
        Price = 1.94
        Genre = 'Country'
        CriticRating = 9.0
} | ConvertTo-DDBItem
Set-DDBItem -TableName 'Music' -Item $item
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-DDBItem`
<a name="dynamodb_UpdateItem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-DDBItem`。

**Tools for PowerShell V5**  
**範例 1：使用分割區索引鍵 SongTitle 和排序索引鍵 Artist，將 DynamoDB 項目的類型屬性設定為 'Rap'**。  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem

$updateDdbItem = @{
    TableName = 'Music'
    Key = $key
    UpdateExpression = 'set Genre = :val1'
    ExpressionAttributeValue = (@{
        ':val1' = ([Amazon.DynamoDBv2.Model.AttributeValue]'Rap')
    })
}
Update-DDBItem @updateDdbItem
```
**輸出：**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateItem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-DDBTable`
<a name="dynamodb_UpdateTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-DDBTable`。

**Tools for PowerShell V5**  
**範例 1：更新特定資料表的佈建輸送量。**  

```
Update-DDBTable -TableName "myTable" -ReadCapacity 10 -WriteCapacity 5
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateTable](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon EC2 範例
<a name="powershell_ec2_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon EC2 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-EC2CapacityReservation`
<a name="ec2_CreateCapacityReservation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-EC2CapacityReservation`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定的屬性建立新的容量保留。**  

```
Add-EC2CapacityReservation -InstanceType m4.xlarge -InstanceCount 2 -AvailabilityZone eu-west-1b -EbsOptimized True -InstancePlatform Windows
```
**輸出：**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-EC2InternetGateway`
<a name="ec2_AttachInternetGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-EC2InternetGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的網際網路閘道，連接到指定的 VPC。**  

```
Add-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
**範例 2：此範例會建立 VPC 和網際網路閘道，然後將網際網路閘道連接至 VPC。**  

```
$vpc = New-EC2Vpc -CidrBlock 10.0.0.0/16
New-EC2InternetGateway | Add-EC2InternetGateway -VpcId $vpc.VpcId
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-EC2NetworkInterface`
<a name="ec2_AttachNetworkInterface_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-EC2NetworkInterface`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的網路介面連接到指定的執行個體。**  

```
Add-EC2NetworkInterface -NetworkInterfaceId eni-12345678 -InstanceId i-1a2b3c4d -DeviceIndex 1
```
**輸出：**  

```
eni-attach-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-EC2Volume`
<a name="ec2_AttachVolume_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-EC2Volume`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的磁碟區連接至指定的執行個體，並使用指定的裝置名稱將其公開。**  

```
Add-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
**輸出：**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : attaching
VolumeId            : vol-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachVolume](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-EC2VpnGateway`
<a name="ec2_AttachVpnGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-EC2VpnGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的虛擬私有閘道，連接至指定的 VPC。**  

```
Add-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
**輸出：**  

```
State        VpcId
-----        -----
attaching    vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Approve-EC2VpcPeeringConnection`
<a name="ec2_AcceptVpcPeeringConnection_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Approve-EC2VpcPeeringConnection`。

**Tools for PowerShell V5**  
**範例 1：此範例會核准請求的 VpcPeeringConnectionId pcx-1dfad234b56ff78be**  

```
Approve-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-1dfad234b56ff78be
```
**輸出：**  

```
AccepterVpcInfo        : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
ExpirationTime         : 1/1/0001 12:00:00 AM
RequesterVpcInfo       : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
Status                 : Amazon.EC2.Model.VpcPeeringConnectionStateReason
Tags                   : {}
VpcPeeringConnectionId : pcx-1dfad234b56ff78be
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AcceptVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Confirm-EC2ProductInstance`
<a name="ec2_ConfirmProductInstance_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Confirm-EC2ProductInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例會判斷指定的產品程式碼，是否與指定的執行個體相關聯。**  

```
Confirm-EC2ProductInstance -ProductCode 774F4FF8 -InstanceId i-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ConfirmProductInstance](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Copy-EC2Image`
<a name="ec2_CopyImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Copy-EC2Image`。

**Tools for PowerShell V5**  
**範例 1：此範例會將「歐盟 (愛爾蘭)」區域中指定的 AMI，複製到「美國西部 (奧勒岡)」區域。如果未指定 -Region，則會將目前的預設區域用作目的地區域。**  

```
Copy-EC2Image -SourceRegion eu-west-1 -SourceImageId ami-12345678 -Region us-west-2 -Name "Copy of ami-12345678"
```
**輸出：**  

```
ami-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CopyImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Copy-EC2Snapshot`
<a name="ec2_CopySnapshot_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Copy-EC2Snapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的快照從「歐盟 (愛爾蘭)」區域，複製到「美國西部 (奧勒岡)」區域。**  

```
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678 -Region us-west-2
```
**範例 2：如果您設定預設區域，並省略區域參數，預設目的地區域即為預設區域。**  

```
Set-DefaultAWSRegion us-west-2
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CopySnapshot](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Deny-EC2VpcPeeringConnection`
<a name="ec2_RejectVpcPeeringConnection_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Deny-EC2VpcPeeringConnection`。

**Tools for PowerShell V5**  
**範例 1：上述範例會拒絕 VpcPeering 請求 id pcx-01a2b3ce45fe67eb8 的請求**  

```
Deny-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-01a2b3ce45fe67eb8
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RejectVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-EC2VgwRoutePropagation`
<a name="ec2_DisableVgwRoutePropagation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-EC2VgwRoutePropagation`。

**Tools for PowerShell V5**  
**範例 1：此範例會禁用 VGW，不讓它將路由自動傳播到指定的路由表。**  

```
Disable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-EC2VpcClassicLink`
<a name="ec2_DisableVpcClassicLink_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-EC2VpcClassicLink`。

**Tools for PowerShell V5**  
**範例 1：此範例停用 vpc-01e23c4a5d6db78e9 的 EC2VpcClassicLink。範例會傳回 True 或 False**  

```
Disable-EC2VpcClassicLink -VpcId vpc-01e23c4a5d6db78e9
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DisableVpcClassicLinkDnsSupport_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-EC2VpcClassicLinkDnsSupport`。

**Tools for PowerShell V5**  
**範例 1：此範例會停用 vpc-0b12d3456a7e8910d 的 ClassicLink DNS 支援**  

```
Disable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Dismount-EC2InternetGateway`
<a name="ec2_DetachInternetGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Dismount-EC2InternetGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的網際網路閘道與指定的 VPC 分開。**  

```
Dismount-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Dismount-EC2NetworkInterface`
<a name="ec2_DetachNetworkInterface_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Dismount-EC2NetworkInterface`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除網路介面與執行個體之間的指定連接。**  

```
Dismount-EC2NetworkInterface -AttachmentId eni-attach-1a2b3c4d -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Dismount-EC2Volume`
<a name="ec2_DetachVolume_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Dismount-EC2Volume`。

**Tools for PowerShell V5**  
**範例 1：此範例會分開指定的磁碟區。**  

```
Dismount-EC2Volume -VolumeId vol-12345678
```
**輸出：**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : detaching
VolumeId            : vol-12345678
```
**範例 2：您也可以指定執行個體 ID 和裝置名稱，確保您分開的是正確的磁碟區。**  

```
Dismount-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachVolume](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Dismount-EC2VpnGateway`
<a name="ec2_DetachVpnGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Dismount-EC2VpnGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的虛擬私有閘道與指定的 VPC 分開。**  

```
Dismount-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2CapacityReservation`
<a name="ec2_ModifyCapacityReservation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2CapacityReservation`。

**Tools for PowerShell V5**  
**範例 1：此範例透過將執行個體計數變更為 1，修改 CapacityReservationId cr-0c1f2345db6f7cdba**  

```
Edit-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba -InstanceCount 1
```
**輸出：**  

```
True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2Host`
<a name="ec2_ModifyHosts_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2Host`。

**Tools for PowerShell V5**  
**範例 1：此範例會將專用主機 h-01e23f4cd567890f3 的 AutoPlacement 設定修改為關閉**  

```
Edit-EC2Host -HostId h-03e09f8cd681609f3 -AutoPlacement off
```
**輸出：**  

```
Successful            Unsuccessful
----------            ------------
{h-01e23f4cd567890f3} {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyHosts](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2IdFormat`
<a name="ec2_ModifyIdFormat_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2IdFormat`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用指定資源類型的較長 ID 格式。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $true
```
**範例 2：此範例會停用指定資源類型的較長 ID 格式。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2ImageAttribute`
<a name="ec2_ModifyImageAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2ImageAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新指定之 AMI 的描述。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Description "New description"
```
**範例 2：此範例會公開 AMI （例如，讓 AWS 帳戶 可以使用）。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserGroup all
```
**範例 3：此範例會將 AMI 設為私有，只讓像您一樣的擁有者使用。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserGroup all
```
**範例 4：此範例會將啟動許可授予指定的 AWS 帳戶。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserId 111122223333
```
**範例 5：此範例會從指定的 移除啟動許可 AWS 帳戶。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserId 111122223333
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2InstanceAttribute`
<a name="ec2_ModifyInstanceAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2InstanceAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定執行個體的執行個體類型。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceType m3.medium
```
**範例 2：此範例透過指定 "simple" 做為單一根 I/O 虛擬化 (SR-IOV) 網路支援參數 -SriovNetSupport，啟用指定之執行個體的增強型聯網。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SriovNetSupport "simple"
```
**範例 3：此範例會修改指定之執行個體的安全群組。執行個體必須在 VPC 中。您必須指定每個安全群組的 ID，而不是名稱。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -Group @( "sg-12345678", "sg-45678901" )
```
**範例 4：此範例會啟用指定之執行個體的 EBS I/O 最佳化。並非所有執行個體類型都可使用此功能。使用 EBS 最佳化執行個體時需支付額外的使用費。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -EbsOptimized $true
```
**範例 5：此範例會啟用指定之執行個體的來源/目的地檢查。若要讓執行個體執行 NAT，此值必須為 'false'。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SourceDestCheck $true
```
**範例 6：此範例會停用指定之執行個體的終止。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -DisableApiTermination $true
```
**範例 7：此範例會變更指定的執行個體，如此才能在從執行個體啟動關機時終止。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceInitiatedShutdownBehavior terminate
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2InstanceCreditSpecification`
<a name="ec2_ModifyInstanceCreditSpecification_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2InstanceCreditSpecification`。

**Tools for PowerShell V5**  
**範例 1：這會啟用執行個體 i-01234567890abcdef 的 T2 無限額度。**  

```
$Credit = New-Object -TypeName Amazon.EC2.Model.InstanceCreditSpecificationRequest
$Credit.InstanceId = "i-01234567890abcdef"
$Credit.CpuCredits = "unlimited"
Edit-EC2InstanceCreditSpecification -InstanceCreditSpecification $Credit
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2NetworkInterfaceAttribute`
<a name="ec2_ModifyNetworkInterfaceAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2NetworkInterfaceAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定的網路介面，如此才能在終止時刪除指定的連接。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Attachment_AttachmentId eni-attach-1a2b3c4d -Attachment_DeleteOnTermination $true
```
**範例 2：此範例會修改指定網路介面的描述。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Description "my description"
```
**範例 3：此範例會修改指定網路介面的安全群組。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Groups sg-1a2b3c4d
```
**範例 4：此範例會停用指定網路介面的來源/目的地檢查。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2ReservedInstance`
<a name="ec2_ModifyReservedInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2ReservedInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定預留執行個體的可用區域、執行個體計數和平台。**  

```
$config = New-Object Amazon.EC2.Model.ReservedInstancesConfiguration
$config.AvailabilityZone = "us-west-2a"
$config.InstanceCount = 1
$config.Platform = "EC2-VPC"

Edit-EC2ReservedInstance `
-ReservedInstancesId @("FE32132D-70D5-4795-B400-AE435EXAMPLE", "0CC556F3-7AB8-4C00-B0E5-98666EXAMPLE") `
-TargetConfiguration $config
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyReservedInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2SnapshotAttribute`
<a name="ec2_ModifySnapshotAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2SnapshotAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例透過設定其 CreateVolumePermission 屬性，將指定的快照設為公有。**  

```
Edit-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission -OperationType Add -GroupName all
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifySnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2SpotFleetRequest`
<a name="ec2_ModifySpotFleetRequest_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2SpotFleetRequest`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新指定 Spot 機群請求的目標容量。**  

```
Edit-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TargetCapacity 10
```
**輸出：**  

```
True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifySpotFleetRequest](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2SubnetAttribute`
<a name="ec2_ModifySubnetAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2SubnetAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用指定子網路的公有 IP 定址。**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $true
```
**範例 2：此範例會停用指定子網路的公有 IP 定址。**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifySubnetAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2VolumeAttribute`
<a name="ec2_ModifyVolumeAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2VolumeAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定磁碟區的指定屬性。由於資料可能不一致，磁碟區的 I/O 操作在暫停後會自動恢復。**  

```
Edit-EC2VolumeAttribute -VolumeId vol-12345678 -AutoEnableIO $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-EC2VpcAttribute`
<a name="ec2_ModifyVpcAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EC2VpcAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用對指定 VPC 的 DNS 主機名稱的支援。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $true
```
**範例 2：此範例會停用對指定 VPC 的 DNS 主機名稱的支援。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $false
```
**範例 3：此範例會啟用對指定 VPC 的 DNS 解析的支援。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $true
```
**範例 4：此範例會停用對指定 VPC 的 DNS 解析的支援。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-EC2VgwRoutePropagation`
<a name="ec2_EnableVgwRoutePropagation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-EC2VgwRoutePropagation`。

**Tools for PowerShell V5**  
**範例 1：此範例可讓指定的 VGW 自動將路由傳播至指定的路由表。**  

```
Enable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-EC2VolumeIO`
<a name="ec2_EnableVolumeIo_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-EC2VolumeIO`。

**Tools for PowerShell V5**  
**範例 1：如果停用 I/O 操作，此範例就會啟用指定磁碟區的 I/O 操作。**  

```
Enable-EC2VolumeIO -VolumeId vol-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableVolumeIo](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-EC2VpcClassicLink`
<a name="ec2_EnableVpcClassicLink_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-EC2VpcClassicLink`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用 ClassicLink 的 VPC vpc-0123456b789b0d12f**  

```
Enable-EC2VpcClassicLink -VpcId vpc-0123456b789b0d12f
```
**輸出：**  

```
True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_EnableVpcClassicLinkDnsSupport_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-EC2VpcClassicLinkDnsSupport`。

**Tools for PowerShell V5**  
**範例 1：此範例可讓 vpc-0b12d3456a7e8910d 支援 ClassicLink 的 DNS 主機名稱解析**  

```
Enable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2AccountAttribute`
<a name="ec2_DescribeAccountAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2AccountAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述您是否可以將執行個體啟動到該區域中的 EC2-Classic 和 EC2-VPC 中，或只能啟動到 EC2-VPC 中。**  

```
(Get-EC2AccountAttribute -AttributeName supported-platforms).AttributeValues
```
**輸出：**  

```
AttributeValue
--------------
EC2
VPC
```
**範例 2：此範例描述您的預設 VPC，或如果區域中沒有預設 VPC，則為 'none'**。  

```
(Get-EC2AccountAttribute -AttributeName default-vpc).AttributeValues
```
**輸出：**  

```
AttributeValue
--------------
vpc-12345678
```
**範例 3：此範例描述您可以執行的隨需執行個體數量上限。**  

```
(Get-EC2AccountAttribute -AttributeName max-instances).AttributeValues
```
**輸出：**  

```
AttributeValue
--------------
20
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAccountAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Address`
<a name="ec2_DescribeAddresses_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Address`。

**Tools for PowerShell V5**  
**範例 1：此範例描述 EC2-Classic 中執行個體的指定彈性 IP 位址。**  

```
Get-EC2Address -AllocationId eipalloc-12345678
```
**輸出：**  

```
AllocationId            : eipalloc-12345678
AssociationId           : eipassoc-12345678
Domain                  : vpc
InstanceId              : i-87654321
NetworkInterfaceId      : eni-12345678
NetworkInterfaceOwnerId : 12345678
PrivateIpAddress        : 10.0.2.172
PublicIp                : 198.51.100.2
```
**範例 2：此範例描述 VPC 中執行個體的彈性 IP 位址。此語法需要 PowerShell 版本 3 或更新版本。**  

```
Get-EC2Address -Filter @{ Name="domain";Values="vpc" }
```
**範例 3：此範例描述 EC2-Classic 中執行個體的指定彈性 IP 位址。**  

```
Get-EC2Address -PublicIp 203.0.113.17
```
**輸出：**  

```
AllocationId            :
AssociationId           :
Domain                  : standard
InstanceId              : i-12345678
NetworkInterfaceId      :
NetworkInterfaceOwnerId :
PrivateIpAddress        :
PublicIp                : 203.0.113.17
```
**範例 4：此範例描述 EC2-Classic 中執行個體的彈性 IP 位址。此語法需要 PowerShell 版本 3 或更新版本。**  

```
Get-EC2Address -Filter @{ Name="domain";Values="standard" }
```
**範例 5：此範例描述您所有的彈性 IP 位址。**  

```
Get-EC2Address
```
**範例 6：此範例會傳回篩選條件中提供的執行個體 ID 的公有和私有 IP**  

```
Get-EC2Address -Region eu-west-1 -Filter @{Name="instance-id";Values="i-0c12d3f4f567ffb89"} | Select-Object PrivateIpAddress, PublicIp
```
**輸出：**  

```
PrivateIpAddress PublicIp
---------------- --------
10.0.0.99        63.36.5.227
```
**範例 7：此範例會擷取所有具有其配置 ID、關聯 ID 和執行個體 ID 的彈性 IP**  

```
Get-EC2Address -Region eu-west-1 | Select-Object InstanceId, AssociationId, AllocationId, PublicIp
```
**輸出：**  

```
InstanceId          AssociationId              AllocationId               PublicIp
----------          -------------              ------------               --------
                                               eipalloc-012e3b456789e1fad 17.212.120.178
i-0c123dfd3415bac67 eipassoc-0e123456bb7890bdb eipalloc-01cd23ebf45f7890c 17.212.124.77
                                               eipalloc-012345678eeabcfad 17.212.225.7
i-0123d405c67e89a0c eipassoc-0c123b456783966ba eipalloc-0123cdd456a8f7892 37.216.52.173
i-0f1bf2f34c5678d09 eipassoc-0e12934568a952d96 eipalloc-0e1c23e4d5e6789e4 37.218.222.278
i-012e3cb4df567e8aa eipassoc-0d1b2fa4d67d03810 eipalloc-0123f456f78a01b58 37.210.82.27
i-0123bcf4b567890e1 eipassoc-01d2345f678903fb1 eipalloc-0e1db23cfef5c45c7 37.215.222.270
```
**範例 8：此範例會擷取值為 'Prod' 且符合標籤索引鍵 'Category' 的 EC2 IP 位址清單**  

```
Get-EC2Address -Filter @{Name="tag:Category";Values="Prod"}
```
**輸出：**  

```
AllocationId            : eipalloc-0123f456f81a01b58
AssociationId           : eipassoc-0d1b23a456d103810
CustomerOwnedIp         :
CustomerOwnedIpv4Pool   :
Domain                  : vpc
InstanceId              : i-012e3cb4df567e1aa
NetworkBorderGroup      : eu-west-1
NetworkInterfaceId      : eni-0123f41d5a60d5f40
NetworkInterfaceOwnerId : 123456789012
PrivateIpAddress        : 192.168.1.84
PublicIp                : 34.250.81.29
PublicIpv4Pool          : amazon
Tags                    : {Category, Name}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAddresses](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2AvailabilityZone`
<a name="ec2_DescribeAvailabilityZones_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2AvailabilityZone`。

**Tools for PowerShell V5**  
**範例 1：此範例描述目前可用區域的可用區域。**  

```
Get-EC2AvailabilityZone
```
**輸出：**  

```
Messages    RegionName    State        ZoneName
--------    ----------    -----        --------
{}          us-west-2     available    us-west-2a
{}          us-west-2     available    us-west-2b
{}          us-west-2     available    us-west-2c
```
**範例 2：此範例描述處於受損狀態的任何可用區域。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
Get-EC2AvailabilityZone -Filter @{ Name="state";Values="impaired" }
```
**範例 3：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立篩選條件。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = "impaired"

Get-EC2AvailabilityZone -Filter $filter
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAvailabilityZones](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2BundleTask`
<a name="ec2_DescribeBundleTasks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2BundleTask`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的綁定任務。**  

```
Get-EC2BundleTask -BundleId bun-12345678
```
**範例 2：此範例描述狀態為「完成」或「失敗」的綁定任務。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "complete", "failed" )

Get-EC2BundleTask -Filter $filter
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeBundleTasks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2CapacityReservation`
<a name="ec2_DescribeCapacityReservations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2CapacityReservation`。

**Tools for PowerShell V5**  
**範例 1：此範例描述區域的一或多個容量保留**  

```
Get-EC2CapacityReservation -Region eu-west-1
```
**輸出：**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeCapacityReservations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2ConsoleOutput`
<a name="ec2_GetConsoleOutput_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2ConsoleOutput`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定 Linux 執行個體的主控台輸出。主控台輸出已編碼。**  

```
Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456
```
**輸出：**  

```
InstanceId          Output
----------          ------
i-0e194d3c47c123637 WyAgICAwLjAwMDAwMF0gQ29tbW...bGU9dHR5UzAgc2Vs
```
**範例 2：此範例會將編碼的主控台輸出儲存在變數中，然後再將其解碼。**  

```
$Output_encoded = (Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456).Output
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Output_encoded))
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetConsoleOutput](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2CustomerGateway`
<a name="ec2_DescribeCustomerGateways_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2CustomerGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的客戶閘道。**  

```
Get-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**輸出：**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
**範例 2：此範例描述狀態為待處理或可用的任何客戶閘道。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2CustomerGateway -Filter $filter
```
**範例 3：此範例描述您所有的客戶閘道。**  

```
Get-EC2CustomerGateway
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeCustomerGateways](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2DhcpOption`
<a name="ec2_DescribeDhcpOptions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2DhcpOption`。

**Tools for PowerShell V5**  
**範例 1：此範例列出您的 DHCP 選項集。**  

```
Get-EC2DhcpOption
```
**輸出：**  

```
DhcpConfigurations                    DhcpOptionsId    Tag
------------------                    -------------    ---
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
{domain-name-servers}                 dopt-3a4b5c6d    {}
```
**範例 2：此範例會取得指定 DHCP 選項集的組態詳細資訊。**  

```
(Get-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d).DhcpConfigurations
```
**輸出：**  

```
Key                    Values
---                    ------
domain-name            {abc.local}
domain-name-servers    {10.0.0.101, 10.0.0.102}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2FlowLog`
<a name="ec2_DescribeFlowLogs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2FlowLog`。

**Tools for PowerShell V5**  
**範例 1：此範例描述日誌目的地類型為 's3' 的一或多個流程日誌**  

```
Get-EC2FlowLog -Filter @{Name="log-destination-type";Values="s3"}
```
**輸出：**  

```
CreationTime             : 2/25/2019 9:07:36 PM
DeliverLogsErrorMessage  :
DeliverLogsPermissionArn :
DeliverLogsStatus        : SUCCESS
FlowLogId                : fl-01b2e3d45f67f8901
FlowLogStatus            : ACTIVE
LogDestination           : arn:aws:s3:::amzn-s3-demo-bucket-dd-tata
LogDestinationType       : s3
LogGroupName             :
ResourceId               : eni-01d2dda3456b7e890
TrafficType              : ALL
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Host`
<a name="ec2_DescribeHosts_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Host`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 EC2 主機詳細資訊。**  

```
Get-EC2Host
```
**輸出：**  

```
AllocationTime    : 3/23/2019 4:55:22 PM
AutoPlacement     : off
AvailabilityZone  : eu-west-1b
AvailableCapacity : Amazon.EC2.Model.AvailableCapacity
ClientToken       :
HostId            : h-01e23f4cd567890f1
HostProperties    : Amazon.EC2.Model.HostProperties
HostReservationId :
Instances         : {}
ReleaseTime       : 1/1/0001 12:00:00 AM
State             : available
Tags              : {}
```
**範例 2：此範例會查詢主機 h-01e23f4cd567899f1 的 AvailableInstanceCapacity**  

```
Get-EC2Host -HostId h-01e23f4cd567899f1 | Select-Object -ExpandProperty AvailableCapacity | Select-Object -expand AvailableInstanceCapacity
```
**輸出：**  

```
AvailableCapacity InstanceType TotalCapacity
----------------- ------------ -------------
11                m4.xlarge    11
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeHosts](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2HostReservationOffering`
<a name="ec2_DescribeHostReservationOfferings_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2HostReservationOffering`。

**Tools for PowerShell V5**  
**範例 1：此範例描述專用主機保留，可供購買給指定篩選條件 'instance-family'，其中 PaymentOption 為 'NoUpfront'**  

```
Get-EC2HostReservationOffering -Filter @{Name="instance-family";Values="m4"} | Where-Object PaymentOption -eq NoUpfront
```
**輸出：**  

```
CurrencyCode   :
Duration       : 94608000
HourlyPrice    : 1.307
InstanceFamily : m4
OfferingId     : hro-0c1f234567890d9ab
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000

CurrencyCode   :
Duration       : 31536000
HourlyPrice    : 1.830
InstanceFamily : m4
OfferingId     : hro-04ad12aaaf34b5a67
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeHostReservationOfferings](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2HostReservationPurchasePreview`
<a name="ec2_GetHostReservationPurchasePreview_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2HostReservationPurchasePreview`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用組態預覽預留購買，這些組態與您專用主機 h-01e23f4cd567890f1 的組態相符。**  

```
Get-EC2HostReservationPurchasePreview -OfferingId hro-0c1f23456789d0ab -HostIdSet h-01e23f4cd567890f1
```
**輸出：**  

```
CurrencyCode Purchase TotalHourlyPrice TotalUpfrontPrice
------------ -------- ---------------- -----------------
             {}       1.307            0.000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetHostReservationPurchasePreview](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2IdFormat`
<a name="ec2_DescribeIdFormat_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2IdFormat`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定資源類型的 ID 格式。**  

```
Get-EC2IdFormat -Resource instance
```
**輸出：**  

```
Resource       UseLongIds
--------       ----------
instance       False
```
**範例 2：此範例描述支援較長 ID 的所有資源類型的 ID 格式。**  

```
Get-EC2IdFormat
```
**輸出：**  

```
Resource       UseLongIds
--------       ----------
reservation    False
instance       False
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2IdentityIdFormat`
<a name="ec2_DescribeIdentityIdFormat_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2IdentityIdFormat`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回指定角色之資源 'image' 的 ID 格式**  

```
Get-EC2IdentityIdFormat -PrincipalArn arn:aws:iam::123456789511:role/JDBC -Resource image
```
**輸出：**  

```
Deadline             Resource UseLongIds
--------             -------- ----------
8/2/2018 11:30:00 PM image    True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeIdentityIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Image`
<a name="ec2_DescribeImages_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Image`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 AMI。**  

```
Get-EC2Image -ImageId ami-12345678
```
**輸出：**  

```
Architecture        : x86_64
BlockDeviceMappings : {/dev/xvda}
CreationDate        : 2014-10-20T00:56:28.000Z
Description         : My image
Hypervisor          : xen
ImageId             : ami-12345678
ImageLocation       : 123456789012/my-image
ImageOwnerAlias     :
ImageType           : machine
KernelId            :
Name                : my-image
OwnerId             : 123456789012
Platform            :
ProductCodes        : {}
Public              : False
RamdiskId           :
RootDeviceName      : /dev/xvda
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         :
Tags                : {Name}
VirtualizationType  : hvm
```
**範例 2：此範例描述您擁有的 AMI。**  

```
Get-EC2Image -owner self
```
**範例 3：此範例描述執行 Microsoft Windows Server 的公有 AMI。**  

```
Get-EC2Image -Filter @{ Name="platform"; Values="windows" }
```
**範例 4：此範例描述 'us-west-2' 區域中的所有公有 AMI。**  

```
Get-EC2Image -Region us-west-2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeImages](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2ImageAttribute`
<a name="ec2_DescribeImageAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2ImageAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定 AMI 的描述。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute description
```
**輸出：**  

```
BlockDeviceMappings : {}
Description         : My image description
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**範例 2：此範例會取得指定 AMI 的啟動許可。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
**輸出：**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {all}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**範例 3：此範例會測試增強型聯網是否已啟用。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute sriovNetSupport
```
**輸出：**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     : simple
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2ImportImageTask`
<a name="ec2_DescribeImportImageTasks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2ImportImageTask`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的映像匯入任務。**  

```
Get-EC2ImportImageTask -ImportTaskId import-ami-hgfedcba
```
**輸出：**  

```
Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
**範例 2：此範例描述所有映像匯入任務。**  

```
Get-EC2ImportImageTask
```
**輸出：**  

```
Architecture    :
Description     : Windows Image 1
Hypervisor      :
ImageId         :
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {}
Status          : deleted
StatusMessage   : User initiated task cancelation

Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeImportImageTasks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2ImportSnapshotTask`
<a name="ec2_DescribeImportSnapshotTasks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2ImportSnapshotTask`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的快照匯入任務。**  

```
Get-EC2ImportSnapshotTask -ImportTaskId import-snap-abcdefgh
```
**輸出：**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
**範例 2：此範例描述所有快照匯入任務。**  

```
Get-EC2ImportSnapshotTask
```
**輸出：**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail 
Disk Image Import 2     import-snap-hgfedcba       Amazon.EC2.Model.SnapshotTaskDetail
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeImportSnapshotTasks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Instance`
<a name="ec2_DescribeInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Instance`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的執行個體。**  

```
(Get-EC2Instance -InstanceId i-12345678).Instances
```
**輸出：**  

```
AmiLaunchIndex        : 0
Architecture          : x86_64
BlockDeviceMappings   : {/dev/sda1}
ClientToken           : TleEy1448154045270
EbsOptimized          : False
Hypervisor            : xen
IamInstanceProfile    : Amazon.EC2.Model.IamInstanceProfile
ImageId               : ami-12345678
InstanceId            : i-12345678
InstanceLifecycle     :
InstanceType          : t2.micro
KernelId              :
KeyName               : my-key-pair
LaunchTime            : 12/4/2015 4:44:40 PM
Monitoring            : Amazon.EC2.Model.Monitoring
NetworkInterfaces     : {ip-10-0-2-172.us-west-2.compute.internal}
Placement             : Amazon.EC2.Model.Placement
Platform              : Windows
PrivateDnsName        : ip-10-0-2-172.us-west-2.compute.internal
PrivateIpAddress      : 10.0.2.172
ProductCodes          : {}
PublicDnsName         : 
PublicIpAddress       : 
RamdiskId             :
RootDeviceName        : /dev/sda1
RootDeviceType        : ebs
SecurityGroups        : {default}
SourceDestCheck       : True
SpotInstanceRequestId :
SriovNetSupport       :
State                 : Amazon.EC2.Model.InstanceState
StateReason           :
StateTransitionReason :
SubnetId              : subnet-12345678
Tags                  : {Name}
VirtualizationType    : hvm
VpcId                 : vpc-12345678
```
**範例 2：此範例描述目前區域中，依預留分組的所有執行個體。若要查看執行個體詳細資訊，請在每個保留物件中展開執行個體集合。**  

```
Get-EC2Instance
```
**輸出：**  

```
GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 226008221399
ReservationId : r-c5df370c

GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 854251627541
ReservationId : r-63e65bab
...
```
**範例 3：此範例說明使用篩選條件查詢特定 VPC 子網路中的 EC2 執行個體。**  

```
(Get-EC2Instance -Filter @{Name="vpc-id";Values="vpc-1a2bc34d"},@{Name="subnet-id";Values="subnet-1a2b3c4d"}).Instances
```
**輸出：**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-01af...82cf180e19 t2.medium    Windows  10.0.0.98                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0374...7e9d5b0c45 t2.xlarge    Windows  10.0.0.53                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**範例 4：此範例說明使用具有多個值的篩選條件，查詢執行中和已停止的 EC2 執行個體**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

(Get-EC2Instance @InstanceParams).Instances
```
**輸出：**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**範例 5：此範例說明使用具有多個值的篩選條件，查詢執行中和已停止的 EC2 執行個體，以及使用 Select-Object Cmdlet 以選擇要輸出的特定值。**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

$SelectParams = @{
    Property = @(
        "InstanceID", "InstanceType", "Platform", "PrivateIpAddress",
        @{Name="Name";Expression={$_.Tags[$_.Tags.Key.IndexOf("Name")].Value}},
        @{Name="State";Expression={$_.State.Name}}
    )
}

$result = Get-EC2Instance @InstanceParams
$result.Instances | Select-Object @SelectParams | Format-Table -AutoSize
```
**輸出：**  

```
InstanceId          InstanceType Platform PrivateIpAddress Name         State
----------          ------------ -------- ---------------- ----         -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7         ec2-name-01  running
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8         ec2-name-02  stopped
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10        ec2-name-03  running
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11        ec2-name-04  stopped
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5         ec2-name-05  running
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6         ec2-name-06  stopped
```
**範例 6：此範例會驗證使用 DryRun 參數取得 EC2 執行個體的許可，而不會實際擷取。注意：如果成功，則會擲回例外狀況，這是預期的行為。**  

```
Get-EC2Tag -DryRun $true
```
**輸出：**  

```
Get-EC2Instance: Request would have succeeded, but DryRun flag is set.
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2InstanceAttribute`
<a name="ec2_DescribeInstanceAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2InstanceAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定之執行個體的執行個體類型。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceType
```
**輸出：**  

```
InstanceType                      : t2.micro
```
**範例 2：此範例描述是否為指定的執行個體啟用增強型聯網。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**輸出：**  

```
SriovNetSupport                   : simple
```
**範例 3：此範例描述指定之執行個體的安全群組。**  

```
(Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute groupSet).Groups
```
**輸出：**  

```
GroupId
-------
sg-12345678
sg-45678901
```
**範例 4：此範例描述指定之執行個體是否啟用 EBS 最佳化。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**輸出：**  

```
EbsOptimized                      : False
```
**範例 5：此範例描述指定之執行個體的 'disableApiTermination' 屬性。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**輸出：**  

```
DisableApiTermination             : False
```
**範例 6：此範例描述指定之執行個體的 'instanceInitiatedShutdownBehavior' 屬性。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
**輸出：**  

```
InstanceInitiatedShutdownBehavior : stop
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2InstanceMetadata`
<a name="ec2_Get-EC2InstanceMetadata_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2InstanceMetadata`。

**Tools for PowerShell V5**  
**範例 1：列出可查詢的可用執行個體中繼資料類別。**  

```
Get-EC2InstanceMetadata -ListCategory
```
**輸出：**  

```
AmiId
LaunchIndex
ManifestPath
AncestorAmiId
BlockDeviceMapping
InstanceId
InstanceType
LocalHostname
LocalIpv4
KernelId
AvailabilityZone
ProductCode
PublicHostname
PublicIpv4
PublicKey
RamdiskId
Region
ReservationId
SecurityGroup
UserData
InstanceMonitoring
IdentityDocument
IdentitySignature
IdentityPkcs7
```
**範例 2：傳回用來啟動執行個體的 Amazon Machine Image (AMI) ID。**  

```
Get-EC2InstanceMetadata -Category AmiId
```
**輸出：**  

```
ami-b2e756ca
```
**範例 3：此範例會查詢執行個體的 JSON 格式化身分文件。**  

```
Get-EC2InstanceMetadata -Category IdentityDocument
{
  "availabilityZone" : "us-west-2a",
  "devpayProductCodes" : null,
  "marketplaceProductCodes" : null,
  "version" : "2017-09-30",
  "instanceId" : "i-01ed50f7e2607f09e",
  "billingProducts" : [ "bp-6ba54002" ],
  "instanceType" : "t2.small",
  "pendingTime" : "2018-03-07T16:26:04Z",
  "imageId" : "ami-b2e756ca",
  "privateIp" : "10.0.0.171",
  "accountId" : "111122223333",
  "architecture" : "x86_64",
  "kernelId" : null,
  "ramdiskId" : null,
  "region" : "us-west-2"
}
```
**範例 4：此範例使用路徑查詢來取得執行個體的網路介面 mac。**  

```
Get-EC2InstanceMetadata -Path "/network/interfaces/macs"
```
**輸出：**  

```
02:80:7f:ef:4c:e0/
```
**範例 5：若有任何與執行個體相關聯的 IAM 角色，則傳回最近一次執行個體設定檔更新的時間，其中又包含執行個體的 LastUpdated 日期、InstanceProfileArn 和 InstanceProfileId。**  

```
Get-EC2InstanceMetadata -Path "/iam/info"
```
**輸出：**  

```
{
  "Code" : "Success",
  "LastUpdated" : "2018-03-08T03:38:40Z",
  "InstanceProfileArn" : "arn:aws:iam::111122223333:instance-profile/MyLaunchRole_Profile",
  "InstanceProfileId" : "AIPAI4...WVK2RW"
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Get-EC2InstanceMetadata](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2InstanceStatus`
<a name="ec2_DescribeInstanceStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2InstanceStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定之執行個體的狀態。**  

```
Get-EC2InstanceStatus -InstanceId i-12345678
```
**輸出：**  

```
AvailabilityZone : us-west-2a
Events           : {}
InstanceId       : i-12345678
InstanceState    : Amazon.EC2.Model.InstanceState
Status           : Amazon.EC2.Model.InstanceStatusSummary
SystemStatus     : Amazon.EC2.Model.InstanceStatusSummary
```

```
$status = Get-EC2InstanceStatus -InstanceId i-12345678
$status.InstanceState
```
**輸出：**  

```
Code    Name
----    ----
16      running
```

```
$status.Status
```
**輸出：**  

```
Details           Status
-------           ------
{reachability}    ok
```

```
$status.SystemStatus
```
**輸出：**  

```
Details           Status
-------           ------
{reachability}    ok
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2InternetGateway`
<a name="ec2_DescribeInternetGateways_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2InternetGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的網際網路閘道。**  

```
Get-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**輸出：**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
```
**範例 2：此範例描述您的所有網際網路閘道。**  

```
Get-EC2InternetGateway
```
**輸出：**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
{}                igw-2a3b4c5d          {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInternetGateways](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2KeyPair`
<a name="ec2_DescribeKeyPairs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2KeyPair`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的金鑰對。**  

```
Get-EC2KeyPair -KeyName my-key-pair
```
**輸出：**  

```
KeyFingerprint                                              KeyName
--------------                                              -------
1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f my-key-pair
```
**範例 2：此範例描述所有金鑰對。**  

```
Get-EC2KeyPair
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeKeyPairs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2NetworkAcl`
<a name="ec2_DescribeNetworkAcls_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2NetworkAcl`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的網路 ACL。**  

```
Get-EC2NetworkAcl -NetworkAclId acl-12345678
```
**輸出：**  

```
Associations : {aclassoc-1a2b3c4d}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {Name}
VpcId        : vpc-12345678
```
**範例 2：此範例描述指定之網路 ACL 的規則。**  

```
(Get-EC2NetworkAcl -NetworkAclId acl-12345678).Entries
```
**輸出：**  

```
CidrBlock    : 0.0.0.0/0
Egress       : True
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767

CidrBlock    : 0.0.0.0/0
Egress       : False
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767
```
**範例 3：此範例描述您的所有網路 ACL。**  

```
Get-EC2NetworkAcl
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeNetworkAcls](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2NetworkInterface`
<a name="ec2_DescribeNetworkInterfaces_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2NetworkInterface`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的網路介面。**  

```
Get-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**輸出：**  

```
Association        :
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
AvailabilityZone   : us-west-2c
Description        :
Groups             : {my-security-group}
MacAddress         : 0a:e9:a6:19:4c:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-107.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.107
PrivateIpAddresses : {ip-10-0-0-107.us-west-2.compute.internal}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : in-use
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
**範例 2：此範例描述您的所有網路介面。**  

```
Get-EC2NetworkInterface
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeNetworkInterfaces](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2NetworkInterfaceAttribute`
<a name="ec2_DescribeNetworkInterfaceAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2NetworkInterfaceAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的網路介面。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Attachment
```
**輸出：**  

```
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
```
**範例 2：此範例描述指定的網路介面。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Description
```
**輸出：**  

```
Description        : My description
```
**範例 3：此範例描述指定的網路介面。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute GroupSet
```
**輸出：**  

```
Groups             : {my-security-group}
```
**範例 4：此範例描述指定的網路介面。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute SourceDestCheck
```
**輸出：**  

```
SourceDestCheck    : True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2PasswordData`
<a name="ec2_GetPasswordData_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2PasswordData`。

**Tools for PowerShell V5**  
**範例 1：此範例會解密 Amazon EC2 指派給指定之 Windows 執行個體管理員帳戶的密碼。由於指定了 pem 檔案，因此會自動採用 -Decrypt 參數的設定。**  

```
Get-EC2PasswordData -InstanceId i-12345678 -PemFile C:\path\my-key-pair.pem
```
**輸出：**  

```
mYZ(PA9?C)Q
```
**範例 2：（僅限 Windows PowerShell) 檢查執行個體，以判斷用來啟動執行個體的金鑰對名稱，然後嘗試在 AWS Toolkit for Visual Studio 的組態存放區中尋找對應的金鑰對資料。如果找到金鑰對資料，則會將密碼解密。**  

```
Get-EC2PasswordData -InstanceId i-12345678 -Decrypt
```
**輸出：**  

```
mYZ(PA9?C)Q
```
**範例 3：傳回執行個體的加密密碼資料。**  

```
Get-EC2PasswordData -InstanceId i-12345678
```
**輸出：**  

```
iVz3BAK/WAXV.....dqt8WeMA==
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPasswordData](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2PlacementGroup`
<a name="ec2_DescribePlacementGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2PlacementGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的置放群組。**  

```
Get-EC2PlacementGroup -GroupName my-placement-group
```
**輸出：**  

```
GroupName             State        Strategy
---------             -----        --------
my-placement-group    available    cluster
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribePlacementGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2PrefixList`
<a name="ec2_DescribePrefixLists_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2PrefixList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取 區域的可用 AWS 服務 字首清單格式**  

```
Get-EC2PrefixList
```
**輸出：**  

```
Cidrs                                          PrefixListId PrefixListName
-----                                          ------------ --------------
{52.94.5.0/24, 52.119.240.0/21, 52.94.24.0/23} pl-6fa54006  com.amazonaws.eu-west-1.dynamodb
{52.218.0.0/17, 54.231.128.0/19}               pl-6da54004  com.amazonaws.eu-west-1.s3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribePrefixLists](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Region`
<a name="ec2_DescribeRegions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Region`。

**Tools for PowerShell V5**  
**範例 1：此範例描述適用於您的區域。**  

```
Get-EC2Region
```
**輸出：**  

```
Endpoint                            RegionName
--------                            ----------
ec2.eu-west-1.amazonaws.com         eu-west-1
ec2.ap-southeast-1.amazonaws.com    ap-southeast-1
ec2.ap-southeast-2.amazonaws.com    ap-southeast-2
ec2.eu-central-1.amazonaws.com      eu-central-1
ec2.ap-northeast-1.amazonaws.com    ap-northeast-1
ec2.us-east-1.amazonaws.com         us-east-1
ec2.sa-east-1.amazonaws.com         sa-east-1
ec2.us-west-1.amazonaws.com         us-west-1
ec2.us-west-2.amazonaws.com         us-west-2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeRegions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2RouteTable`
<a name="ec2_DescribeRouteTables_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2RouteTable`。

**Tools for PowerShell V5**  
**範例 1：此範例描述所有路由表。**  

```
Get-EC2RouteTable
```
**輸出：**  

```
DestinationCidrBlock    : 10.0.0.0/16
DestinationPrefixListId :
GatewayId               : local
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRouteTable
State                   : active
VpcPeeringConnectionId  :

DestinationCidrBlock    : 0.0.0.0/0
DestinationPrefixListId :
GatewayId               : igw-1a2b3c4d
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRoute
State                   : active
VpcPeeringConnectionId  :
```
**範例 2：此範例會傳回指定之路由表的詳細資訊。**  

```
Get-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**範例 3：此範例描述指定之 VPC 的路由表。**  

```
Get-EC2RouteTable -Filter @{ Name="vpc-id"; Values="vpc-1a2b3c4d" }
```
**輸出：**  

```
Associations    : {rtbassoc-12345678}
PropagatingVgws : {}
Routes          : {, }
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeRouteTables](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2ScheduledInstance`
<a name="ec2_DescribeScheduledInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2ScheduledInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的排程執行個體。**  

```
Get-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012
```
**輸出：**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
**範例 2：此範例描述所有已排程的執行個體。**  

```
Get-EC2ScheduledInstance
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2ScheduledInstanceAvailability`
<a name="ec2_DescribeScheduledInstanceAvailability_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2ScheduledInstanceAvailability`。

**Tools for PowerShell V5**  
**範例 1：此範例描述從指定日期開始，每週的週日排程。**  

```
Get-EC2ScheduledInstanceAvailability -Recurrence_Frequency Weekly -Recurrence_Interval 1 -Recurrence_OccurrenceDay 1 -FirstSlotStartTimeRange_EarliestTime 2016-01-31T00:00:00Z -FirstSlotStartTimeRange_LatestTime 2016-01-31T04:00:00Z
```
**輸出：**  

```
AvailabilityZone            : us-west-2b
AvailableInstanceCount      : 20
FirstSlotStartTime          : 1/31/2016 8:00:00 AM
HourlyPrice                 : 0.095
InstanceType                : c4.large
MaxTermDurationInDays       : 366
MinTermDurationInDays       : 366
NetworkPlatform             : EC2-VPC
Platform                    : Linux/UNIX
PurchaseToken               : eyJ2IjoiMSIsInMiOjEsImMiOi...
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
SlotDurationInHours         : 23
TotalScheduledInstanceHours : 1219

...
```
**範例 2：若要縮小結果範圍，您可以針對作業系統、網路和執行個體類型等條件，新增篩選條件。**  

```
-Filter @{ Name="platform";Values="Linux/UNIX" },@{ Name="network-platform";Values="EC2-VPC" },@{ Name="instance-type";Values="c4.large" }
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeScheduledInstanceAvailability](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SecurityGroup`
<a name="ec2_DescribeSecurityGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SecurityGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例描述 VPC 的指定安全群組。使用屬於 VPC 的安全群組時，您必須使用安全群組 ID (-GroupId 參數)，而非名稱 (-GroupName 參數) 參考群組。**  

```
Get-EC2SecurityGroup -GroupId sg-12345678
```
**輸出：**  

```
Description         : default VPC security group
GroupId             : sg-12345678
GroupName           : default
IpPermissions       : {Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {Amazon.EC2.Model.IpPermission}
OwnerId             : 123456789012
Tags                : {}
VpcId               : vpc-12345678
```
**範例 2：此範例描述 EC2-Classic 的指定安全群組。使用 EC2-Classic 的安全群組時，您可以使用群組名稱 (-GroupName 參數) 或群組 ID (-GroupId 參數) 參考安全群組。**  

```
Get-EC2SecurityGroup -GroupName my-security-group
```
**輸出：**  

```
Description         : my security group
GroupId             : sg-45678901
GroupName           : my-security-group
IpPermissions       : {Amazon.EC2.Model.IpPermission, Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {}
OwnerId             : 123456789012
Tags                : {}
VpcId               :
```
**範例 3：此範例會擷取 vpc-0fc1ff23456b789eb 的所有安全群組**  

```
Get-EC2SecurityGroup -Filter @{Name="vpc-id";Values="vpc-0fc1ff23456b789eb"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Snapshot`
<a name="ec2_DescribeSnapshots_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Snapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的快照。**  

```
Get-EC2Snapshot -SnapshotId snap-12345678
```
**輸出：**  

```
DataEncryptionKeyId :
Description         : Created by CreateImage(i-1a2b3c4d) for ami-12345678 from vol-12345678
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            : 100%
SnapshotId          : snap-12345678
StartTime           : 10/23/2014 6:01:28 AM
State               : completed
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 8
```
**範例 2：此範例描述具有 'Name' 標籤的快照。**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" }
```
**範例 3：此範例描述具有值為 'TestValue' 之 'Name' 標籤的快照。**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" -and $_.Tags.Value -eq "TestValue" }
```
**範例 4：此範例描述您的所有快照。**  

```
Get-EC2Snapshot -Owner self
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SnapshotAttribute`
<a name="ec2_DescribeSnapshotAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SnapshotAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定快照的指定屬性。**  

```
Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute ProductCodes
```
**輸出：**  

```
CreateVolumePermissions    ProductCodes    SnapshotId
-----------------------    ------------    ----------
{}                         {}              snap-12345678
```
**範例 2：此範例描述指定快照的指定屬性。**  

```
(Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission).CreateVolumePermissions
```
**輸出：**  

```
Group    UserId
-----    ------
all
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SpotDatafeedSubscription`
<a name="ec2_DescribeSpotDatafeedSubscription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SpotDatafeedSubscription`。

**Tools for PowerShell V5**  
**範例 1：此範例描述您的 Spot 執行個體資料饋送。**  

```
Get-EC2SpotDatafeedSubscription
```
**輸出：**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SpotFleetInstance`
<a name="ec2_DescribeSpotFleetInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SpotFleetInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例描述與指定 Spot 機群請求相關聯的執行個體。**  

```
Get-EC2SpotFleetInstance -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
**輸出：**  

```
InstanceId    InstanceType    SpotInstanceRequestId
----------    ------------    ---------------------
i-f089262a    c3.large        sir-12345678
i-7e8b24a4    c3.large        sir-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSpotFleetInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SpotFleetRequest`
<a name="ec2_DescribeSpotFleetRequests_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SpotFleetRequest`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 Spot 機群請求。**  

```
Get-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE | format-list
```
**輸出：**  

```
ConfigData            : Amazon.EC2.Model.SpotFleetRequestConfigData
CreateTime            : 12/26/2015 8:23:33 AM
SpotFleetRequestId    : sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
SpotFleetRequestState : active
```
**範例 2：此範例描述所有 Spot 機群請求。**  

```
Get-EC2SpotFleetRequest
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SpotFleetRequestHistory`
<a name="ec2_DescribeSpotFleetRequestHistory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SpotFleetRequestHistory`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定 Spot 機群請求的歷程記錄。**  

```
Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z
```
**輸出：**  

```
HistoryRecords     : {Amazon.EC2.Model.HistoryRecord, Amazon.EC2.Model.HistoryRecord...}
LastEvaluatedTime  : 12/26/2015 8:29:11 AM
NextToken          :
SpotFleetRequestId : sfr-088bc5f1-7e7b-451a-bd13-757f10672b93
StartTime          : 12/25/2015 8:00:00 AM
```

```
(Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z).HistoryRecords
```
**輸出：**  

```
EventInformation                     EventType             Timestamp
----------------                     ---------             ---------
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:34 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:05 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSpotFleetRequestHistory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SpotInstanceRequest`
<a name="ec2_DescribeSpotInstanceRequests_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SpotInstanceRequest`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 Spot 執行個體請求。**  

```
Get-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**輸出：**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 4/8/2015 2:51:33 PM
Fault                    :
InstanceId               : i-12345678
LaunchedAvailabilityZone : us-west-2b
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.020000
State                    : active
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {Name}
Type                     : one-time
```
**範例 2：此範例描述所有 Spot 執行個體請求。**  

```
Get-EC2SpotInstanceRequest
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2SpotPriceHistory`
<a name="ec2_DescribeSpotPriceHistory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2SpotPriceHistory`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定執行個體類型和可用區域中，Spot 價格歷程記錄中最後 10 個項目。請注意，為 -AvailabilityZone 參數指定的值，對於提供給 Cmdlet 的 -Region 參數 (未在範例中顯示) 的區域值必須是有效的，或在 Shell 中設定為預設值。此範例命令假設已在環境中設定 'us-west-2' 的預設區域。**  

```
Get-EC2SpotPriceHistory -InstanceType c3.large -AvailabilityZone us-west-2a -MaxResult 10
```
**輸出：**  

```
AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:39:49 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017200
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:38:29 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 6:57:13 AM
...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSpotPriceHistory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Subnet`
<a name="ec2_DescribeSubnets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Subnet`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的子網路。**  

```
Get-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**輸出：**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : available
SubnetId                : subnet-1a2b3c4d
Tags                    : {}
VpcId                   : vpc-12345678
```
**範例 2：此範例描述您的所有子網路。**  

```
Get-EC2Subnet
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSubnets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Tag`
<a name="ec2_DescribeTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Tag`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取資源類型 'image' 的標籤**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="image"}
```
**輸出：**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
Name        ami-0a123b4ccb567a8ea image        Win7-Imported
auto-delete ami-0a123b4ccb567a8ea image        never
```
**範例 2：此範例會擷取所有資源的所有標籤，並會依照資源類型分組**  

```
Get-EC2Tag | Group-Object resourcetype
```
**輸出：**  

```
Count Name                      Group
----- ----                      -----
    9 subnet                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   53 instance                  {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    3 route-table               {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    5 security-group            {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   30 volume                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    1 internet-gateway          {Amazon.EC2.Model.TagDescription}
    3 network-interface         {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    4 elastic-ip                {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    1 dhcp-options              {Amazon.EC2.Model.TagDescription}
    2 image                     {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    3 vpc                       {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
```
**範例 3：此範例顯示用於給定區域，且具有標籤 'auto-delete' 且值為 'no' 的所有資源**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"}
```
**輸出：**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
auto-delete i-0f1bce234d5dd678b   instance     no
auto-delete vol-01d234aa5678901a2 volume       no
auto-delete vol-01234bfb5def6f7b8 volume       no
auto-delete vol-01ccb23f4c5e67890 volume       no
```
**範例 4：此範例會取得具有 'no' 值之標籤 'auto-delete' 的所有資源，並在下一個管道中進一步篩選，以僅剖析 'instance' 資源類型，最終為每個執行個體資源建立 'ThisInstance' 標籤，其值為執行個體 ID 本身**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"} | Where-Object ResourceType -eq "instance" | ForEach-Object {New-EC2Tag -ResourceId $_.ResourceId -Tag @{Key="ThisInstance";Value=$_.ResourceId}}
```
**範例 5：此範例會擷取所有執行個體資源和 'Name' 索引鍵的標籤，並以資料表格式顯示**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="instance"},@{Name="key";Values="Name"} | Select-Object ResourceId, @{Name="Name-Tag";Expression={$PSItem.Value}} | Format-Table -AutoSize
```
**輸出：**  

```
ResourceId          Name-Tag
----------          --------
i-012e3cb4df567e1aa jump1
i-01c23a45d6fc7a89f repro-3
```
**範例 6：此範例會驗證使用 DryRun 參數取得 EC2 標籤的許可權，而不會實際擷取。注意：如果成功，則會擲回例外狀況，這是預期的行為。**  

```
Get-EC2Tag -DryRun $true
```
**輸出：**  

```
Get-EC2Tag: Request would have succeeded, but DryRun flag is set.
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Volume`
<a name="ec2_DescribeVolumes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Volume`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 EBS 磁碟區。**  

```
Get-EC2Volume -VolumeId vol-12345678
```
**輸出：**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 7/17/2015 4:35:19 PM
Encrypted        : False
Iops             : 90
KmsKeyId         :
Size             : 30
SnapshotId       : snap-12345678
State            : in-use
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : standard
```
**範例 2：此範例描述狀態為 'available' 的 EBS 磁碟區。**  

```
Get-EC2Volume -Filter @{ Name="status"; Values="available" }
```
**輸出：**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 12/21/2015 2:31:29 PM
Encrypted        : False
Iops             : 60
KmsKeyId         :
Size             : 20
SnapshotId       : snap-12345678
State            : available
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
...
```
**範例 3：此範例描述所有 EBS 磁碟區。**  

```
Get-EC2Volume
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVolumes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VolumeAttribute`
<a name="ec2_DescribeVolumeAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VolumeAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定之磁碟區的指定屬性。**  

```
Get-EC2VolumeAttribute -VolumeId vol-12345678 -Attribute AutoEnableIO
```
**輸出：**  

```
AutoEnableIO    ProductCodes    VolumeId
------------    ------------    --------
False           {}              vol-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VolumeStatus`
<a name="ec2_DescribeVolumeStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VolumeStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定磁碟區的狀態。**  

```
Get-EC2VolumeStatus -VolumeId vol-12345678
```
**輸出：**  

```
Actions          : {}
AvailabilityZone : us-west-2a
Events           : {}
VolumeId         : vol-12345678
VolumeStatus     : Amazon.EC2.Model.VolumeStatusInfo
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus
```
**輸出：**  

```
Details                         Status
-------                         ------
{io-enabled, io-performance}    ok
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus.Details
```
**輸出：**  

```
Name                            Status
----                            ------
io-enabled                      passed
io-performance                  not-applicable
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVolumeStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2Vpc`
<a name="ec2_DescribeVpcs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2Vpc`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 VPC。**  

```
Get-EC2Vpc -VpcId vpc-12345678
```
**輸出：**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : available
Tags            : {Name}
VpcId           : vpc-12345678
```
**範例 2：此範例描述預設 VPC (每個區域只能有一個)。如果您的帳戶在此區域中支援 EC2-Classic，則沒有預設 VPC。**  

```
Get-EC2Vpc -Filter @{Name="isDefault"; Values="true"}
```
**輸出：**  

```
CidrBlock       : 172.31.0.0/16
DhcpOptionsId   : dopt-12345678
InstanceTenancy : default
IsDefault       : True
State           : available
Tags            : {}
VpcId           : vpc-45678901
```
**範例 3：此範例描述符合指定篩選條件的 VPC (即具有符合值 '10.0.0.0/16' 且處於 'available' 狀態的 CIDR)。**  

```
Get-EC2Vpc -Filter @{Name="cidr"; Values="10.0.0.0/16"},@{Name="state";Values="available"}
```
**範例 4：此範例描述您的所有 VPC。**  

```
Get-EC2Vpc
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpcs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VpcAttribute`
<a name="ec2_DescribeVpcAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VpcAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述 'enableDnsSupport' 屬性。**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsSupport
```
**輸出：**  

```
EnableDnsSupport
----------------
True
```
**範例 2：此範例描述 'enableDnsHostnames' 屬性。**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsHostnames
```
**輸出：**  

```
EnableDnsHostnames
------------------
True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VpcClassicLink`
<a name="ec2_DescribeVpcClassicLink_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VpcClassicLink`。

**Tools for PowerShell V5**  
**範例 1：上述範例傳回具有該區域 ClassicLinkEnabled 狀態的所有 VPC**  

```
Get-EC2VpcClassicLink -Region eu-west-1
```
**輸出：**  

```
ClassicLinkEnabled Tags   VpcId
------------------ ----   -----
False              {Name} vpc-0fc1ff23f45b678eb
False              {}     vpc-01e23c4a5d6db78e9
False              {Name} vpc-0123456b078b9d01f
False              {}     vpc-12cf3b4f
False              {Name} vpc-0b12d3456a7e8901d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DescribeVpcClassicLinkDnsSupport_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VpcClassicLinkDnsSupport`。

**Tools for PowerShell V5**  
**範例 1：此範例描述區域 eu-west-1 的 VPC 的 ClassicLink DNS 支援狀態**  

```
Get-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
**輸出：**  

```
ClassicLinkDnsSupported VpcId
----------------------- -----
False                   vpc-0b12d3456a7e8910d
False                   vpc-12cf3b4f
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VpcEndpoint`
<a name="ec2_DescribeVpcEndpoints_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VpcEndpoint`。

**Tools for PowerShell V5**  
**範例 1：此範例描述區域 eu-west-1 的一或多個 VPC 端點。然後，透過管道將輸出傳輸到下一個命令，其會選取 VpcEndpointId 屬性，並將陣列 VPC ID 傳回為字串陣列**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object -ExpandProperty VpcEndpointId
```
**輸出：**  

```
vpce-01a2ab3f4f5cc6f7d
vpce-01d2b345a6787890b
vpce-0012e34d567890e12
vpce-0c123db4567890123
```
**範例 2：此範例描述區域 eu-west-1 的所有 vpc 端點，並選取 VpcEndpointId、VpcId、ServiceName 和 PrivateDnsEnabled 屬性以表格形式呈現**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object VpcEndpointId, VpcId, ServiceName, PrivateDnsEnabled | Format-Table -AutoSize
```
**輸出：**  

```
VpcEndpointId          VpcId                 ServiceName                         PrivateDnsEnabled
-------------          -----                 -----------                         -----------------
vpce-02a2ab2f2f2cc2f2d vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssm                      True
vpce-01d1b111a1114561b vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2                      True
vpce-0011e23d45167e838 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2messages              True
vpce-0c123db4567890123 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssmmessages              True
```
**範例 3：此範例會將 VPC 端點 vpce-01a2ab3f4f5cc6f7d 的政策文件，匯出至 json 檔案**  

```
Get-EC2VpcEndpoint -Region eu-west-1 -VpcEndpointId vpce-01a2ab3f4f5cc6f7d | Select-Object -expand PolicyDocument | Out-File vpce_policyDocument.json
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpcEndpoints](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VpcEndpointService`
<a name="ec2_DescribeVpcEndpointServices_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VpcEndpointService`。

**Tools for PowerShell V5**  
**範例 1：此範例描述具有給定篩選條件的 EC2 VPC 端點服務，此案例為 com.amazonaws.eu-west-1.ecs。此外，它還會擴展 ServiceDetails 屬性，並顯示詳細資訊**  

```
Get-EC2VpcEndpointService -Region eu-west-1 -MaxResult 5 -Filter @{Name="service-name";Values="com.amazonaws.eu-west-1.ecs"} | Select-Object -ExpandProperty ServiceDetails
```
**輸出：**  

```
AcceptanceRequired         : False
AvailabilityZones          : {eu-west-1a, eu-west-1b, eu-west-1c}
BaseEndpointDnsNames       : {ecs.eu-west-1.vpce.amazonaws.com}
Owner                      : amazon
PrivateDnsName             : ecs.eu-west-1.amazonaws.com
ServiceName                : com.amazonaws.eu-west-1.ecs
ServiceType                : {Amazon.EC2.Model.ServiceTypeDetail}
VpcEndpointPolicySupported : False
```
**範例 2：此範例會擷取所有 EC2 VPC 端點服務，並傳回符合 "ssm" 的 ServiceNames**  

```
Get-EC2VpcEndpointService -Region eu-west-1 | Select-Object -ExpandProperty Servicenames | Where-Object { -match "ssm"}
```
**輸出：**  

```
com.amazonaws.eu-west-1.ssm
com.amazonaws.eu-west-1.ssmmessages
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpcEndpointServices](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VpnConnection`
<a name="ec2_DescribeVpnConnections_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VpnConnection`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的 VPN 連線。**  

```
Get-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**輸出：**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      : Amazon.EC2.Model.VpnConnectionOptions
Routes                       : {Amazon.EC2.Model.VpnStaticRoute}
State                        : available
Tags                         : {}
Type                         : ipsec.1
VgwTelemetry                 : {Amazon.EC2.Model.VgwTelemetry, Amazon.EC2.Model.VgwTelemetry}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**範例 2：此範例描述狀態為待處理或可用的任何 VPN 連線。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnConnection -Filter $filter
```
**範例 3：此範例描述所有 VPN 連線。**  

```
Get-EC2VpnConnection
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpnConnections](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EC2VpnGateway`
<a name="ec2_DescribeVpnGateways_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EC2VpnGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的虛擬私有閘道。**  

```
Get-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**輸出：**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {vpc-12345678}
VpnGatewayId     : vgw-1a2b3c4d
```
**範例 2：此範例描述狀態為待處理或可用的任何虛擬私有閘道。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnGateway -Filter $filter
```
**範例 3：此範例描述您所有的虛擬私有閘道。**  

```
Get-EC2VpnGateway
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeVpnGateways](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Grant-EC2SecurityGroupEgress`
<a name="ec2_AuthorizeSecurityGroupEgress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Grant-EC2SecurityGroupEgress`。

**Tools for PowerShell V5**  
**範例 1：此範例定義 EC2-VPC 指定安全群組的傳出規則。此規則會授予 TCP 連接埠 80 上指定 IP 位址範圍的存取權。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 建立 IpPermission 物件。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**範例 3：此範例會授予 TCP 連接埠 80 上指定之來源安全群組的存取權。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AuthorizeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Grant-EC2SecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Grant-EC2SecurityGroupIngress`。

**Tools for PowerShell V5**  
**範例 1：此範例定義 EC2-VPC 安全群組的傳入規則。這些規則會授予 SSH (連接埠 22) 和 RDC (連接埠 3389) 特定 IP 位址的存取權。請注意，您必須使用安全群組 ID 而非安全性群組名稱，來識別 EC2-VPC 的安全群組。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 建立 IpPermission 物件。**  

```
$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 sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**範例 3：此範例定義 EC2-Classic 安全群組的傳入規則。這些規則會授予 SSH (連接埠 22) 和 RDC (連接埠 3389) 特定 IP 位址的存取權。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**範例 4：使用 PowerShell 版本 2 時，必須使用 New-Object 建立 IpPermission 物件。**  

```
$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 -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**範例 5：此範例會將來自指定來源安全群組 (sg-1a2b3c4d) 的 TCP 連接埠 8081 存取權，授予指定的安全群組 (sg-12345678)。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="8081"; ToPort="8081"; UserIdGroupPairs=$ug } )
```
**範例 6：此範例會將 CIDR 5.5.5.5/32 新增至安全群組 sg-1234abcd 的傳入規則，以描述 TCP 連接埠 22 流量。**  

```
$IpRange = New-Object -TypeName Amazon.EC2.Model.IpRange
$IpRange.CidrIp = "5.5.5.5/32"
$IpRange.Description = "SSH from Office"
$IpPermission = New-Object Amazon.EC2.Model.IpPermission
$IpPermission.IpProtocol = "tcp"
$IpPermission.ToPort = 22
$IpPermission.FromPort = 22
$IpPermission.Ipv4Ranges = $IpRange
Grant-EC2SecurityGroupIngress -GroupId sg-1234abcd -IpPermission $IpPermission
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Import-EC2Image`
<a name="ec2_ImportImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Import-EC2Image`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用冪等性字符，將單一磁碟虛擬機器映像從指定的 Amazon S3 儲存貯體匯入 Amazon EC2。此範例要求具有預設名稱 'vmimport' 的 VM Import 服務角色必須存在，其政策允許 Amazon EC2 存取指定的儲存貯體，如 VM Import 先決條件主題所述。若要使用自訂角色，請使用 `-RoleName` 參數指定角色名稱。**  

```
$container = New-Object Amazon.EC2.Model.ImageDiskContainer
$container.Format="VMDK"
$container.UserBucket = New-Object Amazon.EC2.Model.UserBucket
$container.UserBucket.S3Bucket = "amzn-s3-demo-bucket"
$container.UserBucket.S3Key = "Win_2008_Server_Standard_SP2_64-bit-disk1.vmdk"

$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Windows 2008 Standard Image Import"
    "Platform"="Windows"
    "LicenseType"="AWS"
}

Import-EC2Image -DiskContainer $container @parms
```
**輸出：**  

```
Architecture    : 
Description     : Windows 2008 Standard Image
Hypervisor      : 
ImageId         : 
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        : 2
SnapshotDetails : {}
Status          : active
StatusMessage   : pending
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ImportImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Import-EC2KeyPair`
<a name="ec2_ImportKeyPair_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Import-EC2KeyPair`。

**Tools for PowerShell V5**  
**範例 1：此範例會將公有金鑰匯入 EC2。第一行將公有金鑰檔案 (\$1.pub) 的內容儲存在變數 `$publickey` 中。接著，範例會將公有金鑰檔案的 UTF8 格式，轉換為以 Base64 編碼的字串，並將轉換後的字串儲存在變數 `$pkbase64` 中。在最後一行中，轉換後的公有金鑰會匯入 EC2。Cmdlet 會傳回金鑰指紋和名稱做為結果。**  

```
$publickey=[Io.File]::ReadAllText("C:\Users\TestUser\.ssh\id_rsa.pub")
$pkbase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($publickey))
Import-EC2KeyPair -KeyName Example-user-key -PublicKey $pkbase64
```
**輸出：**  

```
KeyFingerprint                                  KeyName
--------------                                  -------
do:d0:15:8f:79:97:12:be:00:fd:df:31:z3:b1:42:z1 Example-user-key
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ImportKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Import-EC2Snapshot`
<a name="ec2_ImportSnapshot_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Import-EC2Snapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例會將格式為 'VMDK' 的 VM 磁碟映像，匯入 Amazon EBS 快照。此範例需要預設名稱為 'vmimport' 的 VM Import 服務角色，以及允許 Amazon EC2 存取指定的儲存貯體的政策，如 http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/VMImportPrerequisites.html 中的 `VM Import Prequisites` 主題所述。若要使用自訂角色，請使用 `-RoleName` 參數指定角色名稱。**  

```
$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Disk Image Import"
    "DiskContainer_Description" = "Data disk"
    "DiskContainer_Format" = "VMDK"
    "DiskContainer_S3Bucket" = "amzn-s3-demo-bucket"
    "DiskContainer_S3Key" = "datadiskimage.vmdk"
}

Import-EC2Snapshot @parms
```
**輸出：**  

```
Description            ImportTaskId               SnapshotTaskDetail                                                          
-----------------      --------------------       ------------------                                                          
Disk Image Import      import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ImportSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Move-EC2AddressToVpc`
<a name="ec2_MoveAddressToVpc_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Move-EC2AddressToVpc`。

**Tools for PowerShell V5**  
**範例 1：此範例會將公有 IP 位址為 12.345.67.89 的 EC2 執行個體，移至美國東部 (維吉尼亞北部) 區域的 EC2-VPC 平台。**  

```
Move-EC2AddressToVpc -PublicIp 12.345.67.89 -Region us-east-1
```
**範例 2：此範例會將 Get-EC2Instance 命令的結果傳輸至 Move-EC2AddressToVpc Cmdlet。Get-EC2Instance 命令會取得由執行個體 ID 指定的執行個體，然後傳回執行個體的公有 IP 位址屬性。**  

```
(Get-EC2Instance -Instance i-12345678).Instances.PublicIpAddress | Move-EC2AddressToVpc
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [MoveAddressToVpc](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Address`
<a name="ec2_AllocateAddress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Address`。

**Tools for PowerShell V5**  
**範例 1：此範例會配置要與 VPC 中的執行個體搭配使用的彈性 IP 位址。**  

```
New-EC2Address -Domain Vpc
```
**輸出：**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
eipalloc-12345678    vpc         198.51.100.2
```
**範例 2：此範例會配置彈性 IP 位址，以與 EC2-Classic 中的執行個體搭配使用。**  

```
New-EC2Address
```
**輸出：**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
                     standard    203.0.113.17
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AllocateAddress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2CustomerGateway`
<a name="ec2_CreateCustomerGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2CustomerGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立指定的客戶閘道。**  

```
New-EC2CustomerGateway -Type ipsec.1 -PublicIp 203.0.113.12 -BgpAsn 65534
```
**輸出：**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2DhcpOption`
<a name="ec2_CreateDhcpOptions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2DhcpOption`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立指定的 DHCP 選項集。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
$options = @( @{Key="domain-name";Values=@("abc.local")}, @{Key="domain-name-servers";Values=@("10.0.0.101","10.0.0.102")})
New-EC2DhcpOption -DhcpConfiguration $options
```
**輸出：**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
```
**範例 2：使用 PowerShell 版本 2 時，您必須使用 New-Object 建立每一個 DHCP 選項。**  

```
$option1 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option1.Key = "domain-name"
$option1.Values = "abc.local"

$option2 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option2.Key = "domain-name-servers"
$option2.Values = @("10.0.0.101","10.0.0.102")

New-EC2DhcpOption -DhcpConfiguration @($option1, $option2)
```
**輸出：**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2FlowLog`
<a name="ec2_CreateFlowLogs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2FlowLog`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用 'Admin' 角色的權限，為子網路 subnet-1d234567 建立 EC2 流程日誌，並將其傳送至名為 'subnet1-log' 的 cloud-watch-log，以用於所有 'REJECT' 流量**  

```
New-EC2FlowLog -ResourceId "subnet-1d234567" -LogDestinationType cloud-watch-logs -LogGroupName subnet1-log -TrafficType "REJECT" -ResourceType Subnet -DeliverLogsPermissionArn "arn:aws:iam::98765432109:role/Admin"
```
**輸出：**  

```
ClientToken                                  FlowLogIds             Unsuccessful
-----------                                  ----------             ------------
m1VN2cxP3iB4qo//VUKl5EU6cF7gQLOxcqNefvjeTGw= {fl-012fc34eed5678c9d} {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Host`
<a name="ec2_AllocateHosts_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Host`。

**Tools for PowerShell V5**  
**範例 1：此範例會將給定執行個體類型和可用區域的專用主機，配置給您的帳戶**  

```
New-EC2Host -AutoPlacement on -AvailabilityZone eu-west-1b -InstanceType m4.xlarge -Quantity 1
```
**輸出：**  

```
h-01e23f4cd567890f3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AllocateHosts](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2HostReservation`
<a name="ec2_PurchaseHostReservation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2HostReservation`。

**Tools for PowerShell V5**  
**範例 1：此範例會購買預留服務 hro-0c1f23456789d0ab，其組態與您專用主機 h-01e23f4cd567890f1 的組態相符**  

```
New-EC2HostReservation -OfferingId hro-0c1f23456789d0ab HostIdSet h-01e23f4cd567890f1
```
**輸出：**  

```
ClientToken       :
CurrencyCode      :
Purchase          : {hr-0123f4b5d67bedc89}
TotalHourlyPrice  : 1.307
TotalUpfrontPrice : 0.000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PurchaseHostReservation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Image`
<a name="ec2_CreateImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Image`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的執行個體建立具有指定名稱和描述的 AMI。Amazon EC2 會嘗試在建立映像之前徹底關閉執行個體，並在完成時重新啟動執行個體。**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI"
```
**範例 2：此範例會從指定的執行個體建立具有指定名稱和描述的 AMI。Amazon EC2 在未關閉和重新啟動執行個體的情況下建立映像；因此，無法保證所建立映像上的檔案系統完整性。**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -NoReboot $true
```
**範例 3：此範例會建立具有三個磁碟區的 AMI。第一個磁碟區是以 Amazon EBS 快照為基礎。第二個磁碟區是空的 100 GiB Amazon EBS 磁碟區。第三個磁碟區是執行個體儲存體磁碟區。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
$ebsBlock1 = @{SnapshotId="snap-1a2b3c4d"}
$ebsBlock2 = @{VolumeSize=100}

New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -BlockDeviceMapping @( @{DeviceName="/dev/sdf";Ebs=$ebsBlock1}, @{DeviceName="/dev/sdg";Ebs=$ebsBlock2}, @{DeviceName="/dev/sdc";VirtualName="ephemeral0"})
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Instance`
<a name="ec2_RunInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Instance`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 EC2-Classic 或預設 VPC 中，啟動指定 AMI 的單一執行個體。**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -InstanceType m3.medium -KeyName my-key-pair -SecurityGroup my-security-group
```
**範例 2：此範例會在 VPC 中，啟動指定 AMI 的單一執行個體。**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -SubnetId subnet-12345678 -InstanceType t2.micro -KeyName my-key-pair -SecurityGroupId sg-12345678
```
**範例 3：若要新增 EBS 磁碟區或執行個體儲存體磁碟區，請定義區塊型儲存設備映射，並將其新增至命令。此範例會新增執行個體儲存體磁碟區。**  

```
$bdm = New-Object Amazon.EC2.Model.BlockDeviceMapping
$bdm.VirtualName = "ephemeral0"
$bdm.DeviceName = "/dev/sdf"

New-EC2Instance -ImageId ami-12345678 -BlockDeviceMapping $bdm ...
```
**範例 4：若要指定目前的其中一個 Windows AMI，請使用 Get-SSMLatestEC2Image 取得其 AMI ID。此範例會從適用於 Windows Server 2016 的目前基本 AMI 啟動執行個體。**  

```
$ami = (Get-SSMLatestEC2Image -Path 'ami-windows-latest' -ImageName 'WINDOWS*2016*English*Core*BASE').Value

New-EC2Instance -ImageId $ami ...
```
**範例 5：在指定的專用主機環境中啟動執行個體。**  

```
New-EC2Instance -ImageId ami-1a2b3c4d -InstanceType m4.large -KeyName my-key-pair -SecurityGroupId sg-1a2b3c4d  -AvailabilityZone us-west-1a -Tenancy host -HostID h-1a2b3c4d5e6f1a2b3
```
**範例 6：此請求會啟動兩個執行個體，並將具有 Web 伺服器索引鍵和生產值的標籤，套用至執行個體。請求也會將具有成本中心索引鍵和 cc123 值的標籤，套用至所建立的磁碟區 (在此案例中為每個執行個體的根磁碟區)。**  

```
$tag1 = @{ Key="webserver"; Value="production" }
$tag2 = @{ Key="cost-center"; Value="cc123" }

$tagspec1 = new-object Amazon.EC2.Model.TagSpecification
$tagspec1.ResourceType = "instance"
$tagspec1.Tags.Add($tag1)

$tagspec2 = new-object Amazon.EC2.Model.TagSpecification
$tagspec2.ResourceType = "volume"
$tagspec2.Tags.Add($tag2)

New-EC2Instance -ImageId "ami-1a2b3c4d" -KeyName "my-key-pair" -MaxCount 2 -InstanceType "t2.large" -SubnetId "subnet-1a2b3c4d" -TagSpecification $tagspec1,$tagspec2
```
**範例 7：此範例會驗證使用 DryRun 參數啟動 EC2 執行個體的許可權，但不會實際建立執行個體。注意：如果成功，則會擲回例外狀況，這是預期的行為。**  

```
New-EC2Instance -ImageId 'ami-12345678' -InstanceType 't2.micro' -KeyName 'my-key-pair' -Region 'us-west-2' -DryRun $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RunInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2InstanceExportTask`
<a name="ec2_CreateInstanceExportTask_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2InstanceExportTask`。

**Tools for PowerShell V5**  
**範例 1：此範例會將已停止的執行個體 `i-0800b00a00EXAMPLE` 當成虛擬硬碟 (VHD)，匯出至 S3 儲存貯體 `testbucket-export-instances-2019`。目標環境為 `Microsoft`，並新增區域參數，因為執行個體位於 `us-east-1`區域，而使用者的預設 AWS 區域不是 us-east-1。若要取得匯出任務的狀態，請從此命令的結果複製 `ExportTaskId` 值，然後執行 `Get-EC2ExportTask -ExportTaskId export_task_ID_from_results.`**  

```
New-EC2InstanceExportTask -InstanceId i-0800b00a00EXAMPLE -ExportToS3Task_DiskImageFormat VHD -ExportToS3Task_S3Bucket "amzn-s3-demo-bucket" -TargetEnvironment Microsoft -Region us-east-1
```
**輸出：**  

```
Description           : 
ExportTaskId          : export-i-077c73108aEXAMPLE
ExportToS3Task        : Amazon.EC2.Model.ExportToS3Task
InstanceExportDetails : Amazon.EC2.Model.InstanceExportDetails
State                 : active
StatusMessage         :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateInstanceExportTask](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2InternetGateway`
<a name="ec2_CreateInternetGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2InternetGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立網際網路閘道。**  

```
New-EC2InternetGateway
```
**輸出：**  

```
Attachments    InternetGatewayId    Tags
-----------    -----------------    ----
{}             igw-1a2b3c4d         {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2KeyPair`
<a name="ec2_CreateKeyPair_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2KeyPair`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立金鑰對，並在具有指定名稱的檔案中，擷取 PEM 編碼的 RSA 私有金鑰。當您使用 PowerShell 時，編碼必須設定為 ascii，才能產生有效的金鑰。如需詳細資訊，請參閱《 AWS 命令列界面使用者指南》中的建立、顯示和刪除 Amazon EC2 金鑰對 (https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-keypairs.html：//)。**  

```
(New-EC2KeyPair -KeyName "my-key-pair").KeyMaterial | Out-File -Encoding ascii -FilePath C:\path\my-key-pair.pem
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2NetworkAcl`
<a name="ec2_CreateNetworkAcl_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2NetworkAcl`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的 VPC 建立網路 ACL。**  

```
New-EC2NetworkAcl -VpcId vpc-12345678
```
**輸出：**  

```
Associations : {}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {}
VpcId        : vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2NetworkAclEntry`
<a name="ec2_CreateNetworkAclEntry_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2NetworkAclEntry`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的網路 ACL 建立項目。此規則允許來自 UDP 連接埠 53 (DNS) 上任何位置 (0.0.0.0/0) 的傳入流量，傳入任何相關聯的子網路。**  

```
New-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 0.0.0.0/0 -RuleAction allow
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2NetworkInterface`
<a name="ec2_CreateNetworkInterface_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2NetworkInterface`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立指定的網路介面。**  

```
New-EC2NetworkInterface -SubnetId subnet-1a2b3c4d -Description "my network interface" -Group sg-12345678 -PrivateIpAddress 10.0.0.17
```
**輸出：**  

```
Association        :
Attachment         :
AvailabilityZone   : us-west-2c
Description        : my network interface
Groups             : {my-security-group}
MacAddress         : 0a:72:bc:1a:cd:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-17.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.17
PrivateIpAddresses : {}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : pending
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2PlacementGroup`
<a name="ec2_CreatePlacementGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2PlacementGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立具有指定名稱的置放群組。**  

```
New-EC2PlacementGroup -GroupName my-placement-group -Strategy cluster
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreatePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Route`
<a name="ec2_CreateRoute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Route`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的路由表建立指定的路由。路由符合所有流量，並將其傳送至指定的網際網路閘道。**  

```
New-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0 -GatewayId igw-1a2b3c4d
```
**輸出：**  

```
True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateRoute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2RouteTable`
<a name="ec2_CreateRouteTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2RouteTable`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的 VPC 建立路由表。**  

```
New-EC2RouteTable -VpcId vpc-12345678
```
**輸出：**  

```
Associations    : {}
PropagatingVgws : {}
Routes          : {}
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2ScheduledInstance`
<a name="ec2_RunScheduledInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2ScheduledInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟動指定的排程執行個體。**  

```
New-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012 -InstanceCount 1 `
-IamInstanceProfile_Name my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType c4.large `
-LaunchSpecification_SubnetId subnet-12345678`
-LaunchSpecification_SecurityGroupId sg-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RunScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2ScheduledInstancePurchase`
<a name="ec2_PurchaseScheduledInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2ScheduledInstancePurchase`。

**Tools for PowerShell V5**  
**範例 1：此範例會購買排程執行個體。**  

```
$request = New-Object Amazon.EC2.Model.PurchaseRequest
$request.InstanceCount = 1
$request.PurchaseToken = "eyJ2IjoiMSIsInMiOjEsImMiOi..."
New-EC2ScheduledInstancePurchase -PurchaseRequest $request
```
**輸出：**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PurchaseScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2SecurityGroup`
<a name="ec2_CreateSecurityGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2SecurityGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會指定的 VPC 建立安全群組。**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group" -VpcId vpc-12345678
```
**輸出：**  

```
sg-12345678
```
**範例 2：此範例會建立 EC2-Classic 的安全群組。**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group"
```
**輸出：**  

```
sg-45678901
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Snapshot`
<a name="ec2_CreateSnapshot_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Snapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立指定磁碟區的快照。**  

```
New-EC2Snapshot -VolumeId vol-12345678 -Description "This is a test"
```
**輸出：**  

```
DataEncryptionKeyId :
Description         : This is a test
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            :
SnapshotId          : snap-12345678
StartTime           : 12/22/2015 1:28:42 AM
State               : pending
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 20
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2SpotDatafeedSubscription`
<a name="ec2_CreateSpotDatafeedSubscription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2SpotDatafeedSubscription`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立 Spot 執行個體資料饋送。**  

```
New-EC2SpotDatafeedSubscription -Bucket amzn-s3-demo-bucket -Prefix spotdata
```
**輸出：**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Subnet`
<a name="ec2_CreateSubnet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Subnet`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立具有指定 CIDR 的子網路。**  

```
New-EC2Subnet -VpcId vpc-12345678 -CidrBlock 10.0.0.0/24
```
**輸出：**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : pending
SubnetId                : subnet-1a2b3c4d
Tag                     : {}
VpcId                   : vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateSubnet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Tag`
<a name="ec2_CreateTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Tag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將單一標籤新增至指定的資源。標籤索引鍵為 'myTag'，標籤值為 'myTagValue'。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
New-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag"; Value="myTagValue" }
```
**範例 2：此範例會更新或新增指定的標籤至指定的資源。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
New-EC2Tag -Resource i-12345678 -Tag @( @{ Key="myTag"; Value="newTagValue" }, @{ Key="test"; Value="anotherTagValue" } )
```
**範例 3：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立 Tag 參數的標籤。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

New-EC2Tag -Resource i-12345678 -Tag $tag
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Volume`
<a name="ec2_CreateVolume_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Volume`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立指定的磁碟區。**  

```
New-EC2Volume -Size 50 -AvailabilityZone us-west-2a -VolumeType gp2
```
**輸出：**  

```
Attachments      : {}
AvailabilityZone : us-west-2a
CreateTime       : 12/22/2015 1:42:07 AM
Encrypted        : False
Iops             : 150
KmsKeyId         :
Size             : 50
SnapshotId       :
State            : creating
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
```
**範例 2：此範例請求會建立磁碟區，並套用具有堆疊索引鍵和生產值的標籤。**  

```
$tag = @{ Key="stack"; Value="production" }

$tagspec = new-object Amazon.EC2.Model.TagSpecification
$tagspec.ResourceType = "volume"
$tagspec.Tags.Add($tag)

New-EC2Volume -Size 80 -AvailabilityZone "us-west-2a" -TagSpecification $tagspec
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVolume](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2Vpc`
<a name="ec2_CreateVpc_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2Vpc`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立具有指定 CIDR 的 VPC。Amazon VPC 也會為 VPC 建立下列項目：預設 DHCP 選項集、主要路由表，以及預設網路 ACL。**  

```
New-EC2VPC -CidrBlock 10.0.0.0/16
```
**輸出：**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : pending
Tags            : {}
VpcId           : vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVpc](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2VpcEndpoint`
<a name="ec2_CreateVpcEndpoint_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2VpcEndpoint`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 VPC vpc-0fc1ff23f45b678eb 中為服務 com.amazonaws.eu-west-1.s3 建立新的 VPC 端點**  

```
New-EC2VpcEndpoint -ServiceName com.amazonaws.eu-west-1.s3 -VpcId vpc-0fc1ff23f45b678eb
```
**輸出：**  

```
ClientToken VpcEndpoint
----------- -----------
            Amazon.EC2.Model.VpcEndpoint
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVpcEndpoint](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2VpnConnection`
<a name="ec2_CreateVpnConnection_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2VpnConnection`。

**Tools for PowerShell V5**  
**範例 1：此範例會在指定的虛擬私有閘道與指定的客戶閘道之間建立 VPN 連線。輸出包含網路管理員所需的 XML 格式組態資訊。**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d
```
**輸出：**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      :
Routes                       : {}
State                        : pending
Tags                         : {}
Type                         :
VgwTelemetry                 : {}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**範例 2：此範例會建立 VPN 連線，並在具有指定名稱的檔案中擷取組態。**  

```
(New-EC2VpnConnection -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d).CustomerGatewayConfiguration | Out-File C:\path\vpn-configuration.xml
```
**範例 3：此範例會在指定的虛擬私有閘道與指定的客戶閘道之間，建立具有靜態路由的 VPN 連線。**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d -Options_StaticRoutesOnly $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2VpnConnectionRoute`
<a name="ec2_CreateVpnConnectionRoute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2VpnConnectionRoute`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的 VPN 連接建立指定的靜態路由。**  

```
New-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EC2VpnGateway`
<a name="ec2_CreateVpnGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EC2VpnGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立指定的虛擬私有閘道。**  

```
New-EC2VpnGateway -Type ipsec.1
```
**輸出：**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {}
VpnGatewayId     : vgw-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-EC2Address`
<a name="ec2_AssociateAddress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-EC2Address`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的彈性 IP 位址，與 VPC 中指定的執行個體相關聯。**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -AllocationId eipalloc-12345678
```
**輸出：**  

```
eipassoc-12345678
```
**範例 2：此範例會將指定的彈性 IP 位址，與 EC2-Classic 中指定的執行個體相關聯。**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -PublicIp 203.0.113.17
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-EC2DhcpOption`
<a name="ec2_AssociateDhcpOptions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-EC2DhcpOption`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的 DHCP 選項集，與指定的 VPC 相關聯。**  

```
Register-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d -VpcId vpc-12345678
```
**範例 2：此範例會將預設 DHCP 選項集，與指定的 VPC 相關聯。**  

```
Register-EC2DhcpOption -DhcpOptionsId default -VpcId vpc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssociateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-EC2Image`
<a name="ec2_RegisterImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-EC2Image`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用 Amazon S3 中指定的資訊清單檔案，註冊 AMI。**  

```
Register-EC2Image -ImageLocation amzn-s3-demo-bucket/my-web-server-ami/image.manifest.xml -Name my-web-server-ami
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-EC2PrivateIpAddress`
<a name="ec2_AssignPrivateIpAddresses_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-EC2PrivateIpAddress`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的次要私有 IP 位址，指派給指定的網路介面。**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
**範例 2：此範例會建立兩個次要私有 IP 位址，並將其指派給指定的網路介面。**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -SecondaryPrivateIpAddressCount 2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-EC2RouteTable`
<a name="ec2_AssociateRouteTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-EC2RouteTable`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的路由表，與指定的子網路相關聯。**  

```
Register-EC2RouteTable -RouteTableId rtb-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**輸出：**  

```
rtbassoc-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Address`
<a name="ec2_ReleaseAddress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Address`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 VPC 中，發行執行個體的指定彈性 IP 位址。**  

```
Remove-EC2Address -AllocationId eipalloc-12345678 -Force
```
**範例 2：此範例會在 EC2-Classic 中，發行執行個體的指定彈性 IP 位址。**  

```
Remove-EC2Address -PublicIp 198.51.100.2 -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReleaseAddress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2CapacityReservation`
<a name="ec2_CancelCapacityReservation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2CapacityReservation`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消容量保留 cr-0c1f2345db6f7cdba**  

```
Remove-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2CapacityReservation (CancelCapacityReservation)" on target "cr-0c1f2345db6f7cdba".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2CustomerGateway`
<a name="ec2_DeleteCustomerGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2CustomerGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的客戶閘道。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2CustomerGateway (DeleteCustomerGateway)" on Target "cgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2DhcpOption`
<a name="ec2_DeleteDhcpOptions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2DhcpOption`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的 DHCP 選項集。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2DhcpOption (DeleteDhcpOptions)" on Target "dopt-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2FlowLog`
<a name="ec2_DeleteFlowLogs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2FlowLog`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除給定的 FlowLogId fl-01a2b3456a789c01**  

```
Remove-EC2FlowLog -FlowLogId fl-01a2b3456a789c01
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2FlowLog (DeleteFlowLogs)" on target "fl-01a2b3456a789c01".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Host`
<a name="ec2_ReleaseHosts_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Host`。

**Tools for PowerShell V5**  
**範例 1：此範例會發行給定的主機 ID h-0badafd1dcb2f3456**  

```
Remove-EC2Host -HostId h-0badafd1dcb2f3456
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Host (ReleaseHosts)" on target "h-0badafd1dcb2f3456".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Successful            Unsuccessful
----------            ------------
{h-0badafd1dcb2f3456} {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReleaseHosts](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Instance`
<a name="ec2_TerminateInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Instance`。

**Tools for PowerShell V5**  
**範例 1：此範例會終止指定的執行個體 (執行個體可能正在執行，或處於 'stopped' 狀態)。Cmdlet 會在繼續之前提示確認；使用 -Force 切換變數以隱藏提示。**  

```
Remove-EC2Instance -InstanceId i-12345678
```
**輸出：**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TerminateInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2InternetGateway`
<a name="ec2_DeleteInternetGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2InternetGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的網際網路閘道。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2InternetGateway (DeleteInternetGateway)" on Target "igw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2KeyPair`
<a name="ec2_DeleteKeyPair_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2KeyPair`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的金鑰對。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2KeyPair -KeyName my-key-pair
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2KeyPair (DeleteKeyPair)" on Target "my-key-pair".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2NetworkAcl`
<a name="ec2_DeleteNetworkAcl_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2NetworkAcl`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的網路 ACL。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2NetworkAcl -NetworkAclId acl-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAcl (DeleteNetworkAcl)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2NetworkAclEntry`
<a name="ec2_DeleteNetworkAclEntry_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2NetworkAclEntry`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的網路 ACL 移除指定的規則。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAclEntry (DeleteNetworkAclEntry)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2NetworkInterface`
<a name="ec2_DeleteNetworkInterface_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2NetworkInterface`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的網路介面。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkInterface (DeleteNetworkInterface)" on Target "eni-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2PlacementGroup`
<a name="ec2_DeletePlacementGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2PlacementGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的置放群組。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2PlacementGroup -GroupName my-placement-group
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2PlacementGroup (DeletePlacementGroup)" on Target "my-placement-group".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeletePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Route`
<a name="ec2_DeleteRoute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Route`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的路由表刪除指定的路由。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Route (DeleteRoute)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteRoute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2RouteTable`
<a name="ec2_DeleteRouteTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2RouteTable`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的路由表。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2RouteTable (DeleteRouteTable)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2SecurityGroup`
<a name="ec2_DeleteSecurityGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2SecurityGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 EC2-VPC 的指定安全群組。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2SecurityGroup -GroupId sg-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SecurityGroup (DeleteSecurityGroup)" on Target "sg-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：此範例會刪除 EC2-Classic 的指定安全群組。**  

```
Remove-EC2SecurityGroup -GroupName my-security-group -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Snapshot`
<a name="ec2_DeleteSnapshot_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Snapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的快照。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2Snapshot -SnapshotId snap-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Snapshot (DeleteSnapshot)" on target "snap-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2SpotDatafeedSubscription`
<a name="ec2_DeleteSpotDatafeedSubscription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2SpotDatafeedSubscription`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除您的 Spot 執行個體資料饋送。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2SpotDatafeedSubscription
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SpotDatafeedSubscription (DeleteSpotDatafeedSubscription)" on Target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Subnet`
<a name="ec2_DeleteSubnet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Subnet`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的子網路。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Subnet (DeleteSubnet)" on Target "subnet-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteSubnet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Tag`
<a name="ec2_DeleteTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Tag`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的資源刪除指定的標籤，無論標籤值為何。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag" } -Force
```
**範例 2：此範例會從指定的資源刪除指定的標籤，但僅限於標籤值相符時。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag";Value="myTagValue" } -Force
```
**範例 3：此範例會從指定的資源刪除指定的標籤，無論標籤值為何。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
**範例 4：此範例會從指定的資源刪除指定的標籤，但僅限於標籤值相符時。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Volume`
<a name="ec2_DeleteVolume_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Volume`。

**Tools for PowerShell V5**  
**範例 1：此範例會分開指定的磁碟區。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2Volume -VolumeId vol-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Volume (DeleteVolume)" on target "vol-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteVolume](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2Vpc`
<a name="ec2_DeleteVpc_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2Vpc`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的 VPC。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2Vpc -VpcId vpc-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Vpc (DeleteVpc)" on Target "vpc-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteVpc](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2VpnConnection`
<a name="ec2_DeleteVpnConnection_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2VpnConnection`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的 VPN 連線。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnection (DeleteVpnConnection)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2VpnConnectionRoute`
<a name="ec2_DeleteVpnConnectionRoute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2VpnConnectionRoute`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的 VPN 連線移除指定的靜態路由。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnectionRoute (DeleteVpnConnectionRoute)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EC2VpnGateway`
<a name="ec2_DeleteVpnGateway_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EC2VpnGateway`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的虛擬私有閘道。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnGateway (DeleteVpnGateway)" on Target "vgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Request-EC2SpotFleet`
<a name="ec2_RequestSpotFleet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Request-EC2SpotFleet`。

**Tools for PowerShell V5**  
**範例 1：此範例會在可用區域中，以指定執行個體類型的最低價格，建立 Spot 機群請求。如果您的帳戶僅支援 EC2-VPC，Spot 機群會在具有預設子網路的最低價格可用區域中，啟動執行個體。如果您的帳戶支援 EC2-Classic，Spot 機群會在價格最低的可用區域中，啟動 EC2-Classic 中的執行個體。請注意，您支付的價格不會超過請求的指定 Spot 價格。**  

```
$sg = New-Object Amazon.EC2.Model.GroupIdentifier
$sg.GroupId = "sg-12345678"
$lc = New-Object Amazon.EC2.Model.SpotFleetLaunchSpecification
$lc.ImageId = "ami-12345678"
$lc.InstanceType = "m3.medium"
$lc.SecurityGroups.Add($sg) 
Request-EC2SpotFleet -SpotFleetRequestConfig_SpotPrice 0.04 `
-SpotFleetRequestConfig_TargetCapacity 2 `
-SpotFleetRequestConfig_IamFleetRole arn:aws:iam::123456789012:role/my-spot-fleet-role `
-SpotFleetRequestConfig_LaunchSpecification $lc
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RequestSpotFleet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Request-EC2SpotInstance`
<a name="ec2_RequestSpotInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Request-EC2SpotInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例會請求指定子網路中的一次性 Spot 執行個體。請注意，必須為包含指定子網路的 VPC 建立安全群組，而且必須使用網路介面透過 ID 指定。指定網路介面時，必須納入使用網路介面的子網路 ID。**  

```
$n = New-Object Amazon.EC2.Model.InstanceNetworkInterfaceSpecification
$n.DeviceIndex = 0
$n.SubnetId = "subnet-12345678"
$n.Groups.Add("sg-12345678")
Request-EC2SpotInstance -InstanceCount 1 -SpotPrice 0.050 -Type one-time `
-IamInstanceProfile_Arn arn:aws:iam::123456789012:instance-profile/my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType m3.medium `
-LaunchSpecification_NetworkInterface $n
```
**輸出：**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 12/26/2015 7:44:10 AM
Fault                    :
InstanceId               :
LaunchedAvailabilityZone :
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.050000
State                    : open
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {}
Type                     : one-time
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RequestSpotInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Reset-EC2ImageAttribute`
<a name="ec2_ResetImageAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Reset-EC2ImageAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 'launchPermission' 屬性重設為其預設值。根據預設，AMI 為私有。**  

```
Reset-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResetImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Reset-EC2InstanceAttribute`
<a name="ec2_ResetInstanceAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Reset-EC2InstanceAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的執行個體重設 'sriovNetSupport' 屬性。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**範例 2：此範例會為指定的執行個體重設 'ebsOptimized' 屬性。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**範例 3：此範例會為指定的執行個體重設 'sourceDestCheck' 屬性。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sourceDestCheck
```
**範例 4：此範例會為指定的執行個體重設 'disableApiTermination' 屬性。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**範例 5：此範例會為指定的執行個體重設 'instanceInitiatedShutdownBehavior' 屬性。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResetInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Reset-EC2NetworkInterfaceAttribute`
<a name="ec2_ResetNetworkInterfaceAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Reset-EC2NetworkInterfaceAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的網路介面重設來源/目的地檢查作業。**  

```
Reset-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResetNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Reset-EC2SnapshotAttribute`
<a name="ec2_ResetSnapshotAttribute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Reset-EC2SnapshotAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會重設指定快照的指定屬性。**  

```
Reset-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResetSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Restart-EC2Instance`
<a name="ec2_RebootInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Restart-EC2Instance`。

**Tools for PowerShell V5**  
**範例 1：此範例會重新啟動指定的執行個體。**  

```
Restart-EC2Instance -InstanceId i-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RebootInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Revoke-EC2SecurityGroupEgress`
<a name="ec2_RevokeSecurityGroupEgress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Revoke-EC2SecurityGroupEgress`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除 EC2-VPC 的指定安全群組的規則。這會撤銷 TCP 連接埠 80 上，指定之 IP 位址範圍的存取權。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 建立 IpPermission 物件。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**範例 3：此範例會撤銷對 TCP 連接埠 80 上，指定之來源安全群組的存取權。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RevokeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Revoke-EC2SecurityGroupIngress`
<a name="ec2_RevokeSecurityGroupIngress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Revoke-EC2SecurityGroupIngress`。

**Tools for PowerShell V5**  
**範例 1：此範例會從 EC2-VPC 之指定安全群組的指定位址範圍，撤銷對 TCP 連接埠 22 的存取。請注意，您必須使用安全群組 ID 而非安全性群組名稱，來識別 EC2-VPC 的安全群組。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 建立 IpPermission 物件。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**範例 3：此範例會從 EC2-Classic 之指定安全群組的指定位址範圍，撤銷對 TCP 連接埠 22 的存取。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
**範例 4：使用 PowerShell 版本 2 時，必須使用 New-Object 建立 IpPermission 物件。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RevokeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Send-EC2InstanceStatus`
<a name="ec2_ReportInstanceStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Send-EC2InstanceStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例會報告指定執行個體的狀態意見回饋。**  

```
Send-EC2InstanceStatus -Instance i-12345678 -Status impaired -ReasonCode unresponsive
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReportInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-EC2NetworkAclAssociation`
<a name="ec2_ReplaceNetworkAclAssociation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-EC2NetworkAclAssociation`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的網路 ACL，與指定之網路 ACL 關聯的子網路建立關聯。**  

```
Set-EC2NetworkAclAssociation -NetworkAclId acl-12345678 -AssociationId aclassoc-1a2b3c4d
```
**輸出：**  

```
aclassoc-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReplaceNetworkAclAssociation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-EC2NetworkAclEntry`
<a name="ec2_ReplaceNetworkAclEntry_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-EC2NetworkAclEntry`。

**Tools for PowerShell V5**  
**範例 1：此範例會取代指定網路 ACL 的指定項目。新規則允許從指定位址，傳入流量到任何相關聯子網路。**  

```
Set-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 203.0.113.12/24 -RuleAction allow
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReplaceNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-EC2Route`
<a name="ec2_ReplaceRoute_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-EC2Route`。

**Tools for PowerShell V5**  
**範例 1：此範例會取代指定路由表的指定路由。新路由會將指定的流量，傳送至指定的虛擬私有閘道。**  

```
Set-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 10.0.0.0/24 -GatewayId vgw-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReplaceRoute](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-EC2RouteTableAssociation`
<a name="ec2_ReplaceRouteTableAssociation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-EC2RouteTableAssociation`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的路由表，與指定之路由表關聯的子網路建立關聯。**  

```
Set-EC2RouteTableAssociation -RouteTableId rtb-1a2b3c4d -AssociationId rtbassoc-12345678
```
**輸出：**  

```
rtbassoc-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReplaceRouteTableAssociation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-EC2Instance`
<a name="ec2_StartInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-EC2Instance`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟動指定的執行個體。**  

```
Start-EC2Instance -InstanceId i-12345678
```
**輸出：**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
**範例 2：此範例會啟動指定的執行個體。**  

```
@("i-12345678", "i-76543210") | Start-EC2Instance
```
**範例 3：此範例會啟動目前已停止的一組執行個體。Get-EC2Instance 傳回的執行個體物件，會傳輸至 Start-EC2Instance。此範例使用的語法需要 PowerShell 版本 3 或更高版本。**  

```
(Get-EC2Instance -Filter @{ Name="instance-state-name"; Values="stopped"}).Instances | Start-EC2Instance
```
**範例 4：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立每個篩選條件參數的篩選條件。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "instance-state-name"
$filter.Values = "stopped"

(Get-EC2Instance -Filter $filter).Instances | Start-EC2Instance
```
**範例 5：此範例會驗證使用 DryRun 參數啟動 EC2 執行個體的許可權，但不會實際啟動執行個體。注意：如果成功，則會擲回例外狀況，這是預期的行為。**  

```
Start-EC2Instance -InstanceId 'i-0abcdef123456' -Region 'us-west-1' -DryRun $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-EC2InstanceMonitoring`
<a name="ec2_MonitorInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-EC2InstanceMonitoring`。

**Tools for PowerShell V5**  
**範例 1：此範例命令會啟用指定執行個體的詳細監控功能。**  

```
Start-EC2InstanceMonitoring -InstanceId i-12345678
```
**輸出：**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [MonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-EC2ImportTask`
<a name="ec2_CancelImportTask_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-EC2ImportTask`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消指定的匯入任務 (快照或映像匯入)。如有必要，可以使用 `-CancelReason` 參數提供原因。**  

```
Stop-EC2ImportTask -ImportTaskId import-ami-abcdefgh
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelImportTask](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-EC2Instance`
<a name="ec2_StopInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-EC2Instance`。

**Tools for PowerShell V5**  
**範例 1：此範例會停止指定的執行個體。**  

```
Stop-EC2Instance -InstanceId i-12345678
```
**輸出：**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-EC2InstanceMonitoring`
<a name="ec2_UnmonitorInstances_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-EC2InstanceMonitoring`。

**Tools for PowerShell V5**  
**範例 1：此範例命令會停用指定執行個體的詳細監控功能。**  

```
Stop-EC2InstanceMonitoring -InstanceId i-12345678
```
**輸出：**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UnmonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-EC2SpotFleetRequest`
<a name="ec2_CancelSpotFleetRequests_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-EC2SpotFleetRequest`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消指定的 Spot 機群請求，並終止相關聯的 Spot 執行個體。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $true
```
**範例 2：此範例會取消指定的 Spot 機群請求，但不會終止相關聯的 Spot 執行個體。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-EC2SpotInstanceRequest`
<a name="ec2_CancelSpotInstanceRequests_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-EC2SpotInstanceRequest`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消指定的 Spot 執行個體請求。**  

```
Stop-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**輸出：**  

```
SpotInstanceRequestId    State
---------------------    -----
sir-12345678             cancelled
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-EC2Address`
<a name="ec2_DisassociateAddress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-EC2Address`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消指定彈性 IP 位址與 VPC 中指定執行個體的關聯。**  

```
Unregister-EC2Address -AssociationId eipassoc-12345678
```
**範例 2：此範例會取消指定的彈性 IP 位址，與 EC2-Classic 中指定執行個體的關聯。**  

```
Unregister-EC2Address -PublicIp 203.0.113.17
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisassociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-EC2Image`
<a name="ec2_DeregisterImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-EC2Image`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消註冊指定的 AMI。**  

```
Unregister-EC2Image -ImageId ami-12345678
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-EC2PrivateIpAddress`
<a name="ec2_UnassignPrivateIpAddresses_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-EC2PrivateIpAddress`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的網路介面，取消指派指定的私有 IP 位址。**  

```
Unregister-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UnassignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-EC2RouteTable`
<a name="ec2_DisassociateRouteTable_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-EC2RouteTable`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除路由表與子網路之間指定的關聯。**  

```
Unregister-EC2RouteTable -AssociationId rtbassoc-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisassociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-EC2SecurityGroupRuleIngressDescription`
<a name="ec2_UpdateSecurityGroupRuleDescriptionsIngress_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-EC2SecurityGroupRuleIngressDescription`。

**Tools for PowerShell V5**  
**範例 1：更新現有輸入 (傳入) 安全群組規則的描述。**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithUpdatedDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
  "Description" = "Updated rule description"
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithUpdatedDescription
```
**範例 2：移除現有輸入 (傳入) 安全群組規則的描述 (透過省略請求中的參數)。**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithoutDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithoutDescription
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateSecurityGroupRuleDescriptionsIngress](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon ECR 範例
<a name="powershell_ecr_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon ECR 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-ECRLoginCommand`
<a name="ecr_Get-ECRLoginCommand_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ECRLoginCommand`。

**Tools for PowerShell V5**  
**範例 1：傳回一個包含登入資訊的 PSObject，該登入資訊可用於對您的 IAM 主體有權存取的任何 Amazon ECR 註冊表，進行身分驗證。讓呼叫取得授權字符所需的憑證和區域端點，是從 shell 預設值 (由 `Set-AWSCredential/Set-DefaultAWSRegion` 或 `Initialize-AWSDefaultConfiguration` Cmdlet 設定) 取得。您可以搭配 Invoke-Expression 使用 Command 屬性，登入指定的登錄檔，或在需要登入的其他工具中使用傳回的憑證。**  

```
Get-ECRLoginCommand
```
**輸出：**  

```
Username      : AWS
Password      : eyJwYXlsb2Fk...kRBVEFfS0VZIn0=
ProxyEndpoint : https://123456789012.dkr.ecr.us-west-2.amazonaws.com
Endpoint      : https://123456789012.dkr.ecr.us-west-2.amazonaws.com
ExpiresAt     : 9/26/2017 6:08:23 AM
Command       : docker login --username AWS --password eyJwYXlsb2Fk...kRBVEFfS0VZIn0= https://123456789012.dkr.ecr.us-west-2.amazonaws.com
```
**範例 2：擷取 PSObject，其中包含用來做為 docker 登入命令輸入的登入資訊。只要 IAM 主體可以存取該登錄檔，您就可以指定要驗證的任何 Amazon ECR 登錄檔 URI。**  

```
(Get-ECRLoginCommand).Password | docker login --username AWS --password-stdin 012345678910.dkr.ecr.us-east-1.amazonaws.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Get-ECRLoginCommand](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon ECS 範例
<a name="powershell_ecs_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon ECS 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-ECSClusterDetail`
<a name="ecs_DescribeClusters_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ECSClusterDetail`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 描述一或多個 ECS 叢集。**  

```
Get-ECSClusterDetail -Cluster "LAB-ECS-CL" -Include SETTINGS | Select-Object *
```
**輸出：**  

```
LoggedAt         : 12/27/2019 9:27:41 PM
Clusters         : {LAB-ECS-CL}
Failures         : {}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 396
HttpStatusCode   : OK
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeClusters](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ECSClusterList`
<a name="ecs_ListClusters_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ECSClusterList`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會傳回現有 ECS 叢集的清單。**  

```
Get-ECSClusterList
```
**輸出：**  

```
arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListClusters](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ECSClusterService`
<a name="ecs_ListServices_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ECSClusterService`。

**Tools for PowerShell V5**  
**範例 1：此範例列出在預設叢集中執行的所有服務。**  

```
Get-ECSClusterService
```
**範例 2：此範例列出在指定叢集中執行的所有服務。**  

```
Get-ECSClusterService -Cluster myCluster
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListServices](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ECSService`
<a name="ecs_DescribeServices_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ECSService`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何從預設叢集擷取特定服務的詳細資訊。**  

```
Get-ECSService -Service my-hhtp-service
```
**範例 2：此範例示範如何在具名叢集中，擷取執行之特定服務的詳細資訊。**  

```
Get-ECSService -Cluster myCluster -Service my-hhtp-service
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ECSCluster`
<a name="ecs_CreateCluster_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ECSCluster`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會建立新的 Amazon ECS 叢集。**  

```
New-ECSCluster -ClusterName "LAB-ECS-CL" -Setting @{Name="containerInsights"; Value="enabled"}
```
**輸出：**  

```
ActiveServicesCount               : 0
Attachments                       : {}
AttachmentsStatus                 :
CapacityProviders                 : {}
ClusterArn                        : arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
ClusterName                       : LAB-ECS-CL
DefaultCapacityProviderStrategy   : {}
PendingTasksCount                 : 0
RegisteredContainerInstancesCount : 0
RunningTasksCount                 : 0
Settings                          : {containerInsights}
Statistics                        : {}
Status                            : ACTIVE
Tags                              : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateCluster](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ECSService`
<a name="ecs_CreateService_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ECSService`。

**Tools for PowerShell V5**  
**範例 1：此範例命令會在您的預設叢集中，建立名為 `ecs-simple-service` 的服務。服務使用 `ecs-demo` 任務定義，並維護該任務的 10 個執行個體。**  

```
New-ECSService -ServiceName ecs-simple-service -TaskDefinition ecs-demo -DesiredCount 10
```
**範例 2：此範例命令會在您預設叢集中名為 `ecs-simple-service` 的負載平衡器後方建立服務。服務使用 `ecs-demo` 任務定義，並維護該任務的 10 個執行個體。**  

```
$lb = @{
    LoadBalancerName = "EC2Contai-EcsElast-S06278JGSJCM"
    ContainerName = "simple-demo"
    ContainerPort = 80
}        
New-ECSService -ServiceName ecs-simple-service -TaskDefinition ecs-demo -DesiredCount 10 -LoadBalancer $lb
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateService](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ECSCluster`
<a name="ecs_DeleteCluster_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ECSCluster`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會刪除指定的 ECS 叢集。您必須從此叢集取消註冊所有容器執行個體，才能將其刪除。**  

```
Remove-ECSCluster -Cluster "LAB-ECS"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ECSCluster (DeleteCluster)" on target "LAB-ECS".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteCluster](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ECSService`
<a name="ecs_DeleteService_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ECSService`。

**Tools for PowerShell V5**  
**範例 1：刪除預設叢集中名為 'my-http-service' 的服務。服務必須具有所需的計數和執行中的計數 0，如此才能將其刪除。在命令繼續之前，系統會提示您確認。若要略過確認提示，請新增 -Force 切換變數。**  

```
Remove-ECSService -Service my-http-service
```
**範例 2：刪除具名叢集中名為 'my-http-service' 的服務。**  

```
Remove-ECSService -Cluster myCluster -Service my-http-service
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteService](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-ECSClusterSetting`
<a name="ecs_UpdateClusterSettings_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-ECSClusterSetting`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 修改用於 ECS 叢集的設定。**  

```
Update-ECSClusterSetting -Cluster "LAB-ECS-CL" -Setting @{Name="containerInsights"; Value="disabled"}
```
**輸出：**  

```
ActiveServicesCount               : 0
Attachments                       : {}
AttachmentsStatus                 :
CapacityProviders                 : {}
ClusterArn                        : arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
ClusterName                       : LAB-ECS-CL
DefaultCapacityProviderStrategy   : {}
PendingTasksCount                 : 0
RegisteredContainerInstancesCount : 0
RunningTasksCount                 : 0
Settings                          : {containerInsights}
Statistics                        : {}
Status                            : ACTIVE
Tags                              : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateClusterSettings](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-ECSService`
<a name="ecs_UpdateService_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-ECSService`。

**Tools for PowerShell V5**  
**範例 1：此範例命令會更新 `my-http-service` 服務，以使用 `amazon-ecs-sample` 任務定義。**  

```
Update-ECSService -Service my-http-service -TaskDefinition amazon-ecs-sample
```
**範例 2：此範例命令會將所需的 `my-http-service` 服務計數，更新為 10。**  

```
Update-ECSService -Service my-http-service -DesiredCount 10
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateService](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon EFS 範例
<a name="powershell_efs_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon EFS 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Edit-EFSMountTargetSecurityGroup`
<a name="efs_ModifyMountTargetSecurityGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-EFSMountTargetSecurityGroup`。

**Tools for PowerShell V5**  
**範例 1：更新指定掛載目標的有效安全群組。最多可以指定 5 個，格式為 "sg-xxxxxxxx"。**  

```
Edit-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d -SecurityGroup sg-group1,sg-group3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EFSFileSystem`
<a name="efs_DescribeFileSystems_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EFSFileSystem`。

**Tools for PowerShell V5**  
**範例 1：傳回區域中呼叫者帳戶擁有的所有檔案系統的集合。**  

```
Get-EFSFileSystem
```
**輸出：**  

```
CreationTime         : 5/26/2015 4:02:38 PM
CreationToken        : 1a2bff54-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-1a2b3c4d
LifeCycleState       : available
Name                 :
NumberOfMountTargets : 0
OwnerId              : 123456789012
SizeInBytes          : Amazon.ElasticFileSystem.Model.FileSystemSize

CreationTime         : 5/26/2015 4:06:23 PM
CreationToken        : 2b4daa14-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-4d3c2b1a
...
```
**範例 2：傳回指定檔案系統的詳細資訊。**  

```
Get-EFSFileSystem -FileSystemId fs-1a2b3c4d
```
**範例 3：使用建立檔案系統時指定的冪等性建立字符，傳回檔案系統的詳細資訊。**  

```
Get-EFSFileSystem -CreationToken 1a2bff54-85e0-4747-bd95-7bc172c4f555
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeFileSystems](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EFSMountTarget`
<a name="efs_DescribeMountTargets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EFSMountTarget`。

**Tools for PowerShell V5**  
**範例 1：傳回與指定檔案系統相關聯的掛載目標集合。**  

```
Get-EFSMountTarget -FileSystemId fs-1a2b3c4d
```
**輸出：**  

```
FileSystemId       : fs-1a2b3c4d
IpAddress          : 10.0.0.131
LifeCycleState     : available
MountTargetId      : fsmt-1a2b3c4d
NetworkInterfaceId : eni-1a2b3c4d
OwnerId            : 123456789012
SubnetId           : subnet-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMountTargets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EFSMountTargetSecurityGroup`
<a name="efs_DescribeMountTargetSecurityGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EFSMountTargetSecurityGroup`。

**Tools for PowerShell V5**  
**範例 1：傳回目前指派給與掛載目標相關聯之網路介面的安全群組 ID。**  

```
Get-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d
```
**輸出：**  

```
sg-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EFSTag`
<a name="efs_DescribeTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EFSTag`。

**Tools for PowerShell V5**  
**範例 1：傳回目前與指定檔案系統相關聯的標籤集合。**  

```
Get-EFSTag -FileSystemId fs-1a2b3c4d
```
**輸出：**  

```
Key         Value
---         -----
Name        My File System
tagkey1     tagvalue1
tagkey2     tagvalue2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EFSFileSystem`
<a name="efs_CreateFileSystem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EFSFileSystem`。

**Tools for PowerShell V5**  
**範例 1：建立新的空檔案系統。用於確保冪等建立的字符會自動產生，並且可以從傳回物件的 `CreationToken` 成員存取。**  

```
New-EFSFileSystem
```
**輸出：**  

```
CreationTime         : 5/26/2015 4:02:38 PM
CreationToken        : 1a2bff54-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-1a2b3c4d
LifeCycleState       : creating
Name                 :
NumberOfMountTargets : 0
OwnerId              : 123456789012
SizeInBytes          : Amazon.ElasticFileSystem.Model.FileSystemSize
```
**範例 2：使用自訂字符建立新的空檔案系統，以確保冪等建立。**  

```
New-EFSFileSystem -CreationToken "MyUniqueToken"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EFSMountTarget`
<a name="efs_CreateMountTarget_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EFSMountTarget`。

**Tools for PowerShell V5**  
**範例 1：建立檔案系統的新掛載目標。指定的子網路將用於判斷將在其中建立掛載目標的虛擬私有雲端 (VPC)，以及將自動指派的 IP 位址 (來自子網路的位址範圍)。指派的 IP 位址可用於在 Amazon EC2 執行個體上掛載此檔案系統。由於未指定安全群組，為目標建立的網路介面會與子網路 VPC 的預設安全群組相關聯。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**輸出：**  

```
FileSystemId       : fs-1a2b3c4d
IpAddress          : 10.0.0.131
LifeCycleState     : creating
MountTargetId      : fsmt-1a2b3c4d
NetworkInterfaceId : eni-1a2b3c4d
OwnerId            : 123456789012
SubnetId           : subnet-1a2b3c4d
```
**範例 2：為具有自動指派 IP 位址的指定檔案系統，建立新的掛載目標。將掛載目標建立的網路介面，與指定的安全群組相關聯 (最多可指定 5 個，格式為 "sg-xxxxxxxx")**。  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d -SecurityGroup sg-group1,sg-group2,sg-group3
```
**範例 3：為具有指定 IP 位址的指定檔案系統，建立新的掛載目標。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d -IpAddress 10.0.0.131
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateMountTarget](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EFSTag`
<a name="efs_CreateTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EFSTag`。

**Tools for PowerShell V5**  
**範例 1：將標籤集合套用至指定的檔案系統。如果檔案系統上已存在具有指定索引鍵的標籤，則標籤的值會更新。**  

```
New-EFSTag -FileSystemId fs-1a2b3c4d -Tag @{Key="tagkey1";Value="tagvalue1"},@{Key="tagkey2";Value="tagvalue2"}
```
**範例 2：設定指定檔案系統的名稱標籤。使用 Get-EFSFileSystem Cmdlet 時，此值會與其他檔案系統詳細資訊一起傳回。**  

```
New-EFSTag -FileSystemId fs-1a2b3c4d -Tag @{Key="Name";Value="My File System"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EFSFileSystem`
<a name="efs_DeleteFileSystem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EFSFileSystem`。

**Tools for PowerShell V5**  
**範例 1：刪除不再使用的指定檔案系統 (如果檔案系統具有掛載目標，必須先將其移除)。在 Cmdlet 繼續進行之前，系統會提示您確認 - 若要隱藏確認，請使用 `-Force` 切換變數。**  

```
Remove-EFSFileSystem -FileSystemId fs-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EFSMountTarget`
<a name="efs_DeleteMountTarget_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EFSMountTarget`。

**Tools for PowerShell V5**  
**範例 1：刪除指定的掛載目標。在繼續操作之前，系統會提示您確認。若要隱藏提示，請使用 `-Force` 切換變數。請注意，此操作會透過目標強制中斷檔案系統的任何掛載 - 如果可行，您可能需要考慮在執行此命令之前卸載檔案系統。**  

```
Remove-EFSMountTarget -MountTargetId fsmt-1a2b3c4d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteMountTarget](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EFSTag`
<a name="efs_DeleteTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EFSTag`。

**Tools for PowerShell V5**  
**範例 1：從檔案系統刪除一或多個標籤的集合。在 Cmdlet 繼續進行之前，系統會提示您確認 - 若要隱藏確認，請使用 `-Force` 切換變數。**  

```
Remove-EFSTag -FileSystemId fs-1a2b3c4d -TagKey "tagkey1","tagkey2"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon EKS 範例
<a name="powershell_eks_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon EKS 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-EKSResourceTag`
<a name="eks_TagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-EKSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會將為資源指定的標籤，與指定的 resourceArn 建立關聯。**  

```
Add-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD" -Tag @{Name = "EKSPRODCLUSTER"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSCluster`
<a name="eks_DescribeCluster_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSCluster`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會傳回關於 Amazon EKS 叢集的相關描述性資訊。**  

```
Get-EKSCluster -Name "PROD"
```
**輸出：**  

```
Arn                  : arn:aws:eks:us-west-2:012345678912:cluster/PROD
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/25/2019 6:46:17 AM
Endpoint             : https://669608765450FBBE54D1D78A3D71B72C.gr8.us-west-2.eks.amazonaws.com
Identity             : Amazon.EKS.Model.Identity
Logging              : Amazon.EKS.Model.Logging
Name                 : PROD
PlatformVersion      : eks.7
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678912:role/eks-iam-role
Status               : ACTIVE
Tags                 : {}
Version              : 1.14
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeCluster](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSClusterList`
<a name="eks_ListClusters_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSClusterList`。

**Tools for PowerShell V5**  
**範例 1：此 cmdlet 列出指定區域中 中的 Amazon EKS AWS 帳戶 叢集。**  

```
Get-EKSClusterList
```
**輸出：**  

```
 PROD
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListClusters](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSFargateProfile`
<a name="eks_DescribeFargateProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSFargateProfile`。

**Tools for PowerShell V5**  
**範例 1：此 cmdlet 會傳回 AWS Fargate 描述檔的描述性資訊。**  

```
Get-EKSFargateProfile -FargateProfileName "EKSFargate" -ClusterName "TEST"
```
**輸出：**  

```
ClusterName         : TEST
CreatedAt           : 12/26/2019 12:34:47 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargate/42b7a119-e16b-a279-ce97-bdf303adec92
FargateProfileName  : EKSFargate
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : ACTIVE
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSFargateProfileList`
<a name="eks_ListFargateProfiles_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSFargateProfileList`。

**Tools for PowerShell V5**  
**範例 1：此 cmdlet 列出與指定 AWS 帳戶 區域中 中指定叢集相關聯的 AWS Fargate 設定檔。**  

```
Get-EKSFargateProfileList -ClusterName "TEST"
```
**輸出：**  

```
EKSFargate
EKSFargateProfile
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListFargateProfiles](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSNodegroup`
<a name="eks_DescribeNodegroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSNodegroup`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會傳回 Amazon EKS 節點群組的描述性資訊。**  

```
Get-EKSNodegroup -NodegroupName "ProdEKSNodeGroup" -ClusterName "PROD"
```
**輸出：**  

```
AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 10:16:45 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      :
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : CREATING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSNodegroupList`
<a name="eks_ListNodegroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSNodegroupList`。

**Tools for PowerShell V5**  
**範例 1：此 cmdlet 列出與指定區域中 中指定叢集相關聯的 Amazon EKS AWS 帳戶 節點群組。 **  

```
Get-EKSNodegroupList -ClusterName PROD
```
**輸出：**  

```
 ProdEKSNodeGroup
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListNodegroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSResourceTag`
<a name="eks_ListTagsForResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 列出 Amazon EKS 資源的標籤。**  

```
Get-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD"
```
**輸出：**  

```
Key  Value
---  -----
Name EKSPRODCLUSTER
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSUpdate`
<a name="eks_DescribeUpdate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSUpdate`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會針對您的 Amazon EKS 叢集或關聯的受管節點群組，傳回有關更新的描述性資訊。**  

```
Get-EKSUpdate -Name "PROD" -UpdateId "ee708232-7d2e-4ed7-9270-d0b5176f0726"
```
**輸出：**  

```
CreatedAt : 12/25/2019 5:03:07 PM
Errors    : {}
Id        : ee708232-7d2e-4ed7-9270-d0b5176f0726
Params    : {Amazon.EKS.Model.UpdateParam}
Status    : Successful
Type      : LoggingUpdate
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeUpdate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-EKSUpdateList`
<a name="eks_ListUpdates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-EKSUpdateList`。

**Tools for PowerShell V5**  
**範例 1：此 cmdlet 列出與 AWS 帳戶指定區域中 Amazon EKS 叢集或受管節點群組相關聯的更新。**  

```
Get-EKSUpdateList -Name "PROD"
```
**輸出：**  

```
ee708232-7d2e-4ed7-9270-d0b5176f0726
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListUpdates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EKSCluster`
<a name="eks_CreateCluster_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EKSCluster`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立一個稱為 'prod' 的新叢集。**  

```
New-EKSCluster -Name prod -ResourcesVpcConfig @{SubnetIds=@("subnet-0a1b2c3d","subnet-3a2b1c0d");SecurityGroupIds="sg-6979fe18"} -RoleArn "arn:aws:iam::012345678901:role/eks-service-role"
```
**輸出：**  

```
Arn                  : arn:aws:eks:us-west-2:012345678901:cluster/prod
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/10/2018 9:25:31 PM
Endpoint             :
Name                 : prod
PlatformVersion      : eks.3
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678901:role/eks-service-role
Status               : CREATING
Version              : 1.10
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateCluster](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EKSFargateProfile`
<a name="eks_CreateFargateProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EKSFargateProfile`。

**Tools for PowerShell V5**  
**範例 1：此 cmdlet 會為您的 Amazon EKS 叢集建立 AWS Fargate 設定檔。您必須在叢集中至少有一個 Fargate 設定檔，才能在 Fargate 基礎設施上排定 Pod。**  

```
New-EKSFargateProfile -FargateProfileName EKSFargateProfile -ClusterName TEST -Subnet "subnet-02f6ff500ff2067a0", "subnet-0cd976f08d5fbfaae" -PodExecutionRoleArn arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole -Selector @{Namespace="default"}
```
**輸出：**  

```
ClusterName         : TEST
CreatedAt           : 12/26/2019 12:38:21 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargateProfile/20b7a11b-8292-41c1-bc56-ffa5e60f6224
FargateProfileName  : EKSFargateProfile
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : CREATING
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-EKSNodeGroup`
<a name="eks_CreateNodegroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-EKSNodeGroup`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會為 Amazon EKS 叢集建立受管工作節點群組。您只能為叢集建立一個等於叢集目前 Kubernetes 版本的節點群組。針對叢集各自的次要 Kubernetes 版本，使用最新 AMI 發行版本建立所有節點群組。**  

```
New-EKSNodeGroup -NodeGroupName "ProdEKSNodeGroup" -AmiType "AL2_x86_64" -DiskSize 40 -ClusterName "PROD" -ScalingConfig_DesiredSize 2 -ScalingConfig_MinSize 2 -ScalingConfig_MaxSize 5 -InstanceType t3.large -NodeRole "arn:aws:iam::012345678912:role/NodeInstanceRole" -Subnet "subnet-0d1a9fff35efa7691","subnet-0a3f4928edbc224d4"
```
**輸出：**  

```
AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 10:16:45 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      :
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : CREATING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EKSCluster`
<a name="eks_DeleteCluster_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EKSCluster`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會刪除 Amazon EKS 叢集控制平面。**  

```
Remove-EKSCluster -Name "DEV-KUBE-CL"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSCluster (DeleteCluster)" on target "DEV-KUBE-CL".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Arn                  : arn:aws:eks:us-west-2:012345678912:cluster/DEV-KUBE-CL
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/25/2019 9:33:25 AM
Endpoint             : https://02E6D31E3E4F8C15D7BE7F58D527776A.yl4.us-west-2.eks.amazonaws.com
Identity             : Amazon.EKS.Model.Identity
Logging              : Amazon.EKS.Model.Logging
Name                 : DEV-KUBE-CL
PlatformVersion      : eks.7
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678912:role/eks-iam-role
Status               : DELETING
Tags                 : {}
Version              : 1.14
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteCluster](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EKSFargateProfile`
<a name="eks_DeleteFargateProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EKSFargateProfile`。

**Tools for PowerShell V5**  
**範例 1：此 cmdlet 會刪除 AWS Fargate 設定檔。當您刪除 Fargate 設定檔時，使用該設定檔建立的所有在 Fargate 上執行的 Pod，都會遭到刪除。**  

```
Remove-EKSFargateProfile -FargateProfileName "EKSFargate" -ClusterName "TEST"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSFargateProfile (DeleteFargateProfile)" on target "EKSFargate".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

ClusterName         : TEST
CreatedAt           : 12/26/2019 12:34:47 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargate/42b7a119-e16b-a279-ce97-bdf303adec92
FargateProfileName  : EKSFargate
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : DELETING
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EKSNodegroup`
<a name="eks_DeleteNodegroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EKSNodegroup`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會刪除叢集的 Amazon EKS 節點群組。**  

```
Remove-EKSNodegroup -NodegroupName "ProdEKSNodeGroup" -ClusterName "PROD"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSNodegroup (DeleteNodegroup)" on target "ProdEKSNodeGroup".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 11:01:16 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      : Amazon.EKS.Model.NodegroupResources
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : DELETING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-EKSResourceTag`
<a name="eks_UntagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-EKSResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會從 EKS 資源刪除指定的標籤。**  

```
Remove-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD" -TagKey "Name"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSResourceTag (UntagResource)" on target "arn:aws:eks:us-west-2:012345678912:cluster/PROD".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-EKSClusterConfig`
<a name="eks_UpdateClusterConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-EKSClusterConfig`。

**Tools for PowerShell V5**  
**範例 1：更新 Amazon EKS 叢集組態。您的叢集會在更新期間繼續運作。**  

```
Update-EKSClusterConfig -Name "PROD" -Logging_ClusterLogging @{Types="api","audit","authenticator","controllerManager","scheduler",Enabled="True"}
```
**輸出：**  

```
CreatedAt : 12/25/2019 5:03:07 PM
Errors    : {}
Id        : ee708232-7d2e-4ed7-9270-d0b5176f0726
Params    : {Amazon.EKS.Model.UpdateParam}
Status    : InProgress
Type      : LoggingUpdate
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateClusterConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-EKSClusterVersion`
<a name="eks_UpdateClusterVersion_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-EKSClusterVersion`。

**Tools for PowerShell V5**  
**範例 1：此 Cmdlet 會將 Amazon EKS 叢集更新為指定的 Kubernetes 版本。您的叢集會在更新期間繼續運作。**  

```
Update-EKSClusterVersion -Name "PROD-KUBE-CL" -Version 1.14
```
**輸出：**  

```
CreatedAt : 12/26/2019 9:50:37 AM
Errors    : {}
Id        : ef186eff-3b3a-4c25-bcfc-3dcdf9e898a8
Params    : {Amazon.EKS.Model.UpdateParam, Amazon.EKS.Model.UpdateParam}
Status    : InProgress
Type      : VersionUpdate
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateClusterVersion](https://docs.aws.amazon.com/powershell/v5/reference)。

# Elastic Load Balancing - 使用 Tools for PowerShell V5 的版本 1 範例
<a name="powershell_elastic-load-balancing_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Elastic Load Balancing - 第 1 版來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-ELBLoadBalancerToSubnet`
<a name="elastic-load-balancing_AttachLoadBalancerToSubnets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-ELBLoadBalancerToSubnet`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的子網路新增至為指定負載平衡器設定的子網路集。輸出包含子網路的完整清單。**  

```
Add-ELBLoadBalancerToSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**輸出：**  

```
subnet-12345678
subnet-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachLoadBalancerToSubnets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-ELBResourceTag`
<a name="elastic-load-balancing_AddTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-ELBResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會新增指定的標籤至指定的負載平衡器。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
Add-ELBResourceTag -LoadBalancerName my-load-balancer -Tag @{ Key="project";Value="lima" },@{ Key="department";Value="digital-media" }
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立 Tag 參數的標籤。**  

```
$tag = New-Object Amazon.ElasticLoadBalancing.Model.Tag
$tag.Key = "project"
$tag.Value = "lima"
Add-ELBResourceTag -LoadBalancerName my-load-balancer -Tag $tag
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_DisableAvailabilityZonesForLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-ELBAvailabilityZoneForLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的負載平衡器移除指定的可用區域。輸出包含剩餘的可用區域。**  

```
Disable-ELBAvailabilityZoneForLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a
```
**輸出：**  

```
us-west-2b
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Dismount-ELBLoadBalancerFromSubnet`
<a name="elastic-load-balancing_DetachLoadBalancerFromSubnets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Dismount-ELBLoadBalancerFromSubnet`。

**Tools for PowerShell V5**  
**範例 1：此範例會從為指定的負載平衡器的子網路集，移除指定的子網路。輸出包含剩餘的子網路。**  

```
Dismount-ELBLoadBalancerFromSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**輸出：**  

```
subnet-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachLoadBalancerFromSubnets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_ModifyLoadBalancerAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-ELBLoadBalancerAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用指定負載平衡器的跨區域負載平衡。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer -CrossZoneLoadBalancing_Enabled $true
```
**範例 2：此範例會停用指定負載平衡器的連接耗盡。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer -ConnectionDraining_Enabled $false
```
**範例 3：此範例會啟用指定之負載平衡器的存取記錄。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer `
>> -AccessLog_Enabled $true `
>> -AccessLog_S3BucketName amzn-s3-demo-logging-bucket `
>> -AccessLog_S3BucketPrefix my-app/prod `
>> -AccessLog_EmitInterval 60
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_EnableAvailabilityZonesForLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-ELBAvailabilityZoneForLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的可用區域新增至指定的負載平衡器。輸出包含可用區域的完整清單。**  

```
Enable-ELBAvailabilityZoneForLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a
```
**輸出：**  

```
us-west-2a
us-west-2b
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELBInstanceHealth`
<a name="elastic-load-balancing_DescribeInstanceHealth_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELBInstanceHealth`。

**Tools for PowerShell V5**  
**範例 1：此範例描述向指定負載平衡器註冊的執行個體狀態。**  

```
Get-ELBInstanceHealth -LoadBalancerName my-load-balancer
```
**輸出：**  

```
Description                   InstanceId                    ReasonCode                    State
-----------                   ----------                    ----------                    -----
N/A                           i-87654321                    N/A                           InService
Instance has failed at lea... i-12345678                    Instance                      OutOfService
```
**範例 2：此範例描述向指定負載平衡器註冊的指定執行個體狀態。**  

```
Get-ELBInstanceHealth -LoadBalancerName my-load-balancer -Instance i-12345678
```
**範例 3：此範例顯示指定執行個體狀態的完整描述。**  

```
(Get-ELBInstanceHealth -LoadBalancerName my-load-balancer -Instance i-12345678).Description
```
**輸出：**  

```
Instance has failed at least the UnhealthyThreshold number of health checks consecutively.
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELBLoadBalancer`
<a name="elastic-load-balancing_DescribeLoadBalancers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELBLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例列出負載平衡器的名稱。**  

```
Get-ELBLoadBalancer | format-table -property LoadBalancerName
```
**輸出：**  

```
LoadBalancerName
----------------
my-load-balancer
my-other-load-balancer
my-internal-load-balancer
```
**範例 2：此範例描述指定的負載平衡器。**  

```
Get-ELBLoadBalancer -LoadBalancerName my-load-balancer
```
**輸出：**  

```
AvailabilityZones         : {us-west-2a, us-west-2b}
BackendServerDescriptions : {Amazon.ElasticLoadBalancing.Model.BackendServerDescription}
CanonicalHostedZoneName   : my-load-balancer-1234567890.us-west-2.elb.amazonaws.com
CanonicalHostedZoneNameID : Z3DZXE0EXAMPLE
CreatedTime               : 4/11/2015 12:12:45 PM
DNSName                   : my-load-balancer-1234567890.us-west-2.elb.amazonaws.com
HealthCheck               : Amazon.ElasticLoadBalancing.Model.HealthCheck
Instances                 : {i-207d9717, i-afefb49b}
ListenerDescriptions      : {Amazon.ElasticLoadBalancing.Model.ListenerDescription}
LoadBalancerName          : my-load-balancer
Policies                  : Amazon.ElasticLoadBalancing.Model.Policies
Scheme                    : internet-facing
SecurityGroups            : {sg-a61988c3}
SourceSecurityGroup       : Amazon.ElasticLoadBalancing.Model.SourceSecurityGroup
Subnets                   : {subnet-15aaab61}
VPCId                     : vpc-a01106c2
```
**範例 3：此範例說明目前 AWS 區域中所有負載平衡器。**  

```
Get-ELBLoadBalancer
```
**範例 4：此範例描述所有可用 AWS 區域的所有負載平衡器。**  

```
Get-AWSRegion | % { Get-ELBLoadBalancer -Region $_ }
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_DescribeLoadBalancerAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELBLoadBalancerAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的負載平衡器的屬性。**  

```
Get-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer
```
**輸出：**  

```
AccessLog              : Amazon.ElasticLoadBalancing.Model.AccessLog
AdditionalAttributes   : {}
ConnectionDraining     : Amazon.ElasticLoadBalancing.Model.ConnectionDraining
ConnectionSettings     : Amazon.ElasticLoadBalancing.Model.ConnectionSettings
CrossZoneLoadBalancing : Amazon.ElasticLoadBalancing.Model.CrossZoneLoadBalancing
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELBLoadBalancerPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例描述與指定負載平衡器相關聯的政策。**  

```
Get-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer
```
**輸出：**  

```
PolicyAttributeDescriptions             PolicyName                              PolicyTypeName
---------------------------             ----------                              --------------
{ProxyProtocol}                         my-ProxyProtocol-policy                 ProxyProtocolPolicyType
{CookieName}                            my-app-cookie-policy                    AppCookieStickinessPolicyType
```
**範例 2：此範例描述指定政策的屬性。**  

```
(Get-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-ProxyProtocol-policy).PolicyAttributeDescriptions
```
**輸出：**  

```
AttributeName    AttributeValue
-------------    --------------
ProxyProtocol    true
```
**範例 3：此範例描述預先定義的政策，包括範例政策。範例政策的名稱具有 ELBSample- 字首。**  

```
Get-ELBLoadBalancerPolicy
```
**輸出：**  

```
PolicyAttributeDescriptions             PolicyName                              PolicyTypeName
---------------------------             ----------                              --------------
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-05               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-03               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-02               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2014-10               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2014-01               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2011-08               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSample-ELBDefaultCipherPolicy        SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSample-OpenSSLDefaultCipherPolicy    SSLNegotiationPolicyType
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLoadBalancerPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELBLoadBalancerPolicyType`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicyTypes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELBLoadBalancerPolicyType`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得 Elastic Load Balancing 支援的政策類型。**  

```
Get-ELBLoadBalancerPolicyType
```
**輸出：**  

```
Description                             PolicyAttributeTypeDescriptions         PolicyTypeName
-----------                             -------------------------------         --------------
Stickiness policy with session lifet... {CookieExpirationPeriod}                LBCookieStickinessPolicyType
Policy that controls authentication ... {PublicKeyPolicyName}                   BackendServerAuthenticationPolicyType
Listener policy that defines the cip... {Protocol-SSLv2, Protocol-TLSv1, Pro... SSLNegotiationPolicyType
Policy containing a list of public k... {PublicKey}                             PublicKeyPolicyType
Stickiness policy with session lifet... {CookieName}                            AppCookieStickinessPolicyType
Policy that controls whether to incl... {ProxyProtocol}                         ProxyProtocolPolicyType
```
**範例 2：此範例描述指定的政策類型。**  

```
Get-ELBLoadBalancerPolicyType -PolicyTypeName ProxyProtocolPolicyType
```
**輸出：**  

```
Description                             PolicyAttributeTypeDescriptions         PolicyTypeName
-----------                             -------------------------------         --------------
Policy that controls whether to incl... {ProxyProtocol}                         ProxyProtocolPolicyType
```
**範例 3：此範例顯示指定之政策類型的完整描述。**  

```
(Get-ELBLoadBalancerPolicyType -PolicyTypeName).Description
```
**輸出：**  

```
Policy that controls whether to include the IP address and port of the originating request for TCP messages. 
This policy operates on TCP/SSL listeners only
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLoadBalancerPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELBResourceTag`
<a name="elastic-load-balancing_DescribeTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELBResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例列出指定負載平衡器的標籤。**  

```
Get-ELBResourceTag -LoadBalancerName @("my-load-balancer","my-internal-load-balancer")
```
**輸出：**  

```
LoadBalancerName             Tags
----------------             ----
my-load-balancer             {project, department}
my-internal-load-balancer    {project, department}
```
**範例 2：此範例描述指定負載平衡器的標籤。**  

```
(Get-ELBResourceTag -LoadBalancerName my-load-balancer).Tags
```
**輸出：**  

```
Key           Value
---           -----
project       lima
department    digital-media
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Join-ELBSecurityGroupToLoadBalancer`
<a name="elastic-load-balancing_ApplySecurityGroupsToLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Join-ELBSecurityGroupToLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定負載平衡器的目前安全群組，更換為指定的安全群組。**  

```
Join-ELBSecurityGroupToLoadBalancer -LoadBalancerName my-load-balancer -SecurityGroup sg-87654321
```
**輸出：**  

```
sg-87654321
```
**範例 2：若要保留目前的安全群組，並指定額外的安全群組，請同時指定現有和新的安全群組。**  

```
Join-ELBSecurityGroupToLoadBalancer -LoadBalancerName my-load-balancer -SecurityGroup @("sg-12345678", "sg-87654321")
```
**輸出：**  

```
sg-12345678
sg-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ApplySecurityGroupsToLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELBAppCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateAppCookieStickinessPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELBAppCookieStickinessPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立黏性政策，該政策遵循指定應用程式產生之 Cookie 的黏性工作階段生命週期。**  

```
New-ELBAppCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-app-cookie-policy -CookieName my-app-cookie
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAppCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELBLBCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateLbCookieStickinessPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELBLBCookieStickinessPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立具黏性工作階段生命週期的黏性政策，而該黏性工作階段生命週期是由指定的到期期間 (以秒為單位) 控制。**  

```
New-ELBLBCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy -CookieExpirationPeriod 60
```
**範例 2：此範例會建立具黏性工作階段生命週期的黏性政策，其黏性工作階段生命週期是由瀏覽器的生命週期 (使用者代理程式) 控制。**  

```
New-ELBLBCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLbCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELBLoadBalancer`
<a name="elastic-load-balancing_CreateLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELBLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 VPC 中建立具有 HTTP 接聽程式的負載平衡器。**  

```
$httpListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpListener.Protocol = "http"
$httpListener.LoadBalancerPort = 80
$httpListener.InstanceProtocol = "http"
$httpListener.InstancePort = 80
New-ELBLoadBalancer -LoadBalancerName my-vpc-load-balancer -SecurityGroup sg-a61988c3 -Subnet subnet-15aaab61 -Listener $httpListener

my-vpc-load-balancer-1234567890.us-west-2.elb.amazonaws.com
```
**範例 2：此範例會在 EC2-Classic 中建立具有 HTTP 接聽程式的負載平衡器。**  

```
New-ELBLoadBalancer -LoadBalancerName my-classic-load-balancer -AvailabilityZone us-west-2a` -Listener $httpListener
```
**輸出：**  

```
my-classic-load-balancer-123456789.us-west-2.elb.amazonaws.com
```
**範例 3：此範例會使用 HTTPS 接聽程式建立負載平衡器。**  

```
$httpsListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpsListener.Protocol = "https"
$httpsListener.LoadBalancerPort = 443
$httpsListener.InstanceProtocol = "http"
$httpsListener.InstancePort = 80 
$httpsListener.SSLCertificateId="arn:aws:iam::123456789012:server-certificate/my-server-cert"
New-ELBLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a -Listener $httpsListener

my-load-balancer-123456789.us-west-2.elb.amazonaws.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELBLoadBalancerListener`
<a name="elastic-load-balancing_CreateLoadBalancerListeners_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELBLoadBalancerListener`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 HTTPS 接聽程式新增至指定的負載平衡器。**  

```
$httpsListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpsListener.Protocol = "https"
$httpsListener.LoadBalancerPort = 443
$httpsListener.InstanceProtocol = "https"
$httpsListener.InstancePort = 443 
$httpsListener.SSLCertificateId="arn:aws:iam::123456789012:server-certificate/my-server-cert"
New-ELBLoadBalancerListener -LoadBalancerName my-load-balancer -Listener $httpsListener
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_CreateLoadBalancerPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELBLoadBalancerPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的負載平衡器建立新的代理通訊協定政策。**  

```
$attribute = New-Object Amazon.ElasticLoadBalancing.Model.PolicyAttribute -Property @{
         AttributeName="ProxyProtocol"
         AttributeValue="True"
    }
New-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-ProxyProtocol-policy -PolicyTypeName ProxyProtocolPolicyType -PolicyAttribute $attribute
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-ELBInstanceWithLoadBalancer`
<a name="elastic-load-balancing_RegisterInstancesWithLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-ELBInstanceWithLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會向指定的負載平衡器註冊指定的 EC2 執行個體。**  

```
Register-ELBInstanceWithLoadBalancer -LoadBalancerName my-load-balancer -Instance i-12345678
```
**輸出：**  

```
InstanceId
----------
i-12345678
i-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterInstancesWithLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELBInstanceFromLoadBalancer`
<a name="elastic-load-balancing_DeregisterInstancesFromLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELBInstanceFromLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的負載平衡器移除指定的 EC2 執行個體。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-ELBInstanceFromLoadBalancer -LoadBalancerName my-load-balancer -Instance i-12345678
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBInstanceFromLoadBalancer (DeregisterInstancesFromLoadBalancer)" on Target
"Amazon.ElasticLoadBalancing.Model.Instance".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

InstanceId
----------
i-87654321
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterInstancesFromLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELBLoadBalancer`
<a name="elastic-load-balancing_DeleteLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELBLoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的負載平衡器。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-ELBLoadBalancer -LoadBalancerName my-load-balancer
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancer (DeleteLoadBalancer)" on Target "my-load-balancer".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELBLoadBalancerListener`
<a name="elastic-load-balancing_DeleteLoadBalancerListeners_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELBLoadBalancerListener`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定負載平衡器之連接埠 80 上的接聽程式。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-ELBLoadBalancerListener -LoadBalancerName my-load-balancer -LoadBalancerPort 80
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancerListener (DeleteLoadBalancerListeners)" on Target "80".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DeleteLoadBalancerPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELBLoadBalancerPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的負載平衡器刪除指定的政策。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。**  

```
Remove-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancerPolicy (DeleteLoadBalancerPolicy)" on Target "my-duration-cookie-policy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELBResourceTag`
<a name="elastic-load-balancing_RemoveTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELBResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的負載平衡器移除指定的標籤。除非也指定 Force 參數，否則在繼續操作之前，系統會提示您確認。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
Remove-ELBResourceTag -LoadBalancerName my-load-balancer -Tag @{ Key="project" }
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELBResourceTag (RemoveTags)" on target "Amazon.ElasticLoadBalancing.Model.TagKeyOnly".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**範例 2：使用 Powershell 版本 2 時，必須使用 New-Object 來建立 Tag 參數的標籤。**  

```
$tag = New-Object Amazon.ElasticLoadBalancing.Model.TagKeyOnly
$tag.Key = "project"
Remove-ELBResourceTag -Tag $tag -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELBHealthCheck`
<a name="elastic-load-balancing_ConfigureHealthCheck_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELBHealthCheck`。

**Tools for PowerShell V5**  
**範例 1：此範例會設定指定之負載平衡器的運作狀態檢查設定。**  

```
Set-ELBHealthCheck -LoadBalancerName my-load-balancer `
>> -HealthCheck_HealthyThreshold 2 `
>> -HealthCheck_UnhealthyThreshold 2 `
>> -HealthCheck_Target "HTTP:80/ping" `
>> -HealthCheck_Interval 30 `
>> -HealthCheck_Timeout 3
```
**輸出：**  

```
HealthyThreshold   : 2
Interval           : 30
Target             : HTTP:80/ping
Timeout            : 3
UnhealthyThreshold : 2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ConfigureHealthCheck](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELBLoadBalancerListenerSSLCertificate`
<a name="elastic-load-balancing_SetLoadBalancerListenerSslCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELBLoadBalancerListenerSSLCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會取代終止指定之接聽程式 SSL 連線的憑證。**  

```
Set-ELBLoadBalancerListenerSSLCertificate -LoadBalancerName my-load-balancer `
>> -LoadBalancerPort 443 `
>> -SSLCertificateId "arn:aws:iam::123456789012:server-certificate/new-server-cert"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetLoadBalancerListenerSslCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELBLoadBalancerPolicyForBackendServer`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesForBackendServer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELBLoadBalancerPolicyForBackendServer`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定之連接埠的政策，取代為指定的政策。**  

```
Set-ELBLoadBalancerPolicyForBackendServer -LoadBalancerName my-load-balancer -InstancePort 80 -PolicyName my-ProxyProtocol-policy
```
**範例 2：此範例會移除與指定連接埠相關聯的所有政策。**  

```
Set-ELBLoadBalancerPolicyForBackendServer -LoadBalancerName my-load-balancer -InstancePort 80
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetLoadBalancerPoliciesForBackendServer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELBLoadBalancerPolicyOfListener`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesOfListener_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELBLoadBalancerPolicyOfListener`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定接聽程式的政策，取代為指定的政策。**  

```
Set-ELBLoadBalancerPolicyOfListener -LoadBalancerName my-load-balancer -LoadBalancerPort 443 -PolicyName my-SSLNegotiation-policy
```
**範例 2：此範例會移除與指定接聽程式相關聯的所有政策。**  

```
Set-ELBLoadBalancerPolicyOfListener -LoadBalancerName my-load-balancer -LoadBalancerPort 443
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetLoadBalancerPoliciesOfListener](https://docs.aws.amazon.com/powershell/v5/reference)。

# Elastic Load Balancing - 使用 Tools for PowerShell V5 的版本 2 範例
<a name="powershell_elastic-load-balancing-v2_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Elastic Load Balancing - 第 2 版來執行動作並實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_AddListenerCertificates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-ELB2ListenerCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會將其他憑證新增至指定的接聽程式。**  

```
Add-ELB2ListenerCertificate -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618' -Certificate @{CertificateArn = 'arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97'}
```
**輸出：**  

```
CertificateArn                                                                      IsDefault
--------------                                                                      ---------
arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97 False
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-ELB2Tag`
<a name="elastic-load-balancing-v2_AddTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-ELB2Tag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將新標籤新增至指定的 `AWS.Tools.ElasticLoadBalancingV2` 資源。**  

```
Add-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Tag @{Key = 'productVersion'; Value = '1.0.0'}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-ELB2Listener`
<a name="elastic-load-balancing-v2_ModifyListener_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-ELB2Listener`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的接聽程式預設動作，修改為固定回應。**  

```
$newDefaultAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{
    "FixedResponseConfig" = @{
    "ContentType" = "text/plain"
    "MessageBody" = "Hello World"
    "StatusCode" = "200"
  }
  "Type" = [Amazon.ElasticLoadBalancingV2.ActionTypeEnum]::FixedResponse
}

Edit-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/d19f2f14974db685' -Port 8080 -DefaultAction $newDefaultAction
```
**輸出：**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/d19f2f14974db685
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676
Port            : 8080
Protocol        : HTTP
SslPolicy       :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyListener](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_ModifyLoadBalancerAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-ELB2LoadBalancerAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定負載平衡器的屬性。**  

```
Edit-ELB2LoadBalancerAttribute -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Attribute @{Key = 'deletion_protection.enabled'; Value = 'true'}
```
**輸出：**  

```
Key                                             Value
---                                             -----
deletion_protection.enabled                     true
access_logs.s3.enabled                          false
access_logs.s3.bucket
access_logs.s3.prefix
idle_timeout.timeout_seconds                    60
routing.http2.enabled                           true
routing.http.drop_invalid_header_fields.enabled false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-ELB2Rule`
<a name="elastic-load-balancing-v2_ModifyRule_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-ELB2Rule`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定的接聽程式規則組態。**  

```
$newRuleCondition = [Amazon.ElasticLoadBalancingV2.Model.RuleCondition]@{
    "PathPatternConfig" = @{
    "Values" = "/login1","/login2","/login3" 
  }
  "Field" = "path-pattern"
}

Edit-ELB2Rule -RuleArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc' -Condition $newRuleCondition
```
**輸出：**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 10
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyRule](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_ModifyTargetGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-ELB2TargetGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定目標群組的屬性。**  

```
Edit-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -HealthCheckIntervalSecond 60 -HealthCheckPath '/index.html' -HealthCheckPort 8080
```
**輸出：**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 60
HealthCheckPath            : /index.html
HealthCheckPort            : 8080
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 5
LoadBalancerArns           : {}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970
TargetGroupName            : test-tg
TargetType                 : instance
UnhealthyThresholdCount    : 2
VpcId                      : vpc-2cfd7000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_ModifyTargetGroupAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-ELB2TargetGroupAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定目標群組的 deregistration\$1delay 屬性。**  

```
Edit-ELB2TargetGroupAttribute -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -Attribute @{Key = 'deregistration_delay.timeout_seconds'; Value = 600}
```
**輸出：**  

```
Key                                   Value
---                                   -----
stickiness.enabled                    false
deregistration_delay.timeout_seconds  600
stickiness.type                       lb_cookie
stickiness.lb_cookie.duration_seconds 86400
slow_start.duration_seconds           0
load_balancing.algorithm.type         round_robin
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2AccountLimit`
<a name="elastic-load-balancing-v2_DescribeAccountLimits_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2AccountLimit`。

**Tools for PowerShell V5**  
**範例 1：此命令列出給定區域的 ELB2 帳戶限制。**  

```
Get-ELB2AccountLimit
```
**輸出：**  

```
Max  Name
---  ----
3000 target-groups
1000 targets-per-application-load-balancer
50   listeners-per-application-load-balancer
100  rules-per-application-load-balancer
50   network-load-balancers
3000 targets-per-network-load-balancer
500  targets-per-availability-zone-per-network-load-balancer
50   listeners-per-network-load-balancer
5    condition-values-per-alb-rule
5    condition-wildcards-per-alb-rule
100  target-groups-per-application-load-balancer
5    target-groups-per-action-on-application-load-balancer
1    target-groups-per-action-on-network-load-balancer
50   application-load-balancers
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2Listener`
<a name="elastic-load-balancing-v2_DescribeListeners_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2Listener`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定 ALB/NLB 的接聽程式。**  

```
Get-ELB2Listener -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**輸出：**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/1dac07c21187d41e
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f
Port            : 80
Protocol        : HTTP
SslPolicy       : 

Certificates    : {Amazon.ElasticLoadBalancingV2.Model.Certificate}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f
Port            : 443
Protocol        : HTTPS
SslPolicy       : ELBSecurityPolicy-2016-08
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeListeners](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_DescribeListenerCertificates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2ListenerCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定接聽程式的憑證。**  

```
Get-ELB2ListenerCertificate -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**輸出：**  

```
CertificateArn                                                                      IsDefault
--------------                                                                      ---------
arn:aws:acm:us-east-1:123456789012:certificate/5fc7c092-68bf-4862-969c-22fd48b6e17c True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2LoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示給定區域的所有負載平衡器。**  

```
Get-ELB2LoadBalancer
```
**輸出：**  

```
AvailabilityZones     : {us-east-1c}
CanonicalHostedZoneId : Z26RNL4JYFTOTI
CreatedTime           : 6/22/18 11:21:50 AM
DNSName               : test-elb1234567890-238d34ad8d94bc2e.elb.us-east-1.amazonaws.com
IpAddressType         : ipv4
LoadBalancerArn       : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/test-elb1234567890/238d34ad8d94bc2e
LoadBalancerName      : test-elb1234567890
Scheme                : internet-facing
SecurityGroups        : {}
State                 : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState
Type                  : network
VpcId                 : vpc-2cf00000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_DescribeLoadBalancerAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2LoadBalancerAttribute`。

**Tools for PowerShell V5**  
**範例 1：此命令說明給定負載平衡器的屬性。**  

```
Get-ELB2LoadBalancerAttribute -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/test-elb/238d34ad8d94bc2e'
```
**輸出：**  

```
Key                               Value
---                               -----
access_logs.s3.enabled            false
load_balancing.cross_zone.enabled true
access_logs.s3.prefix             
deletion_protection.enabled       false
access_logs.s3.bucket
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2Rule`
<a name="elastic-load-balancing-v2_DescribeRules_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2Rule`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定接聽程式 ARN 的接聽程式規則。**  

```
Get-ELB2Rule -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**輸出：**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 1
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/2286fff5055e0f79

Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 2
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/14e7b036567623ba

Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {}
IsDefault  : True
Priority   : default
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/853948cf3aa9b2bf
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeRules](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2SSLPolicy`
<a name="elastic-load-balancing-v2_DescribeSslPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2SSLPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例列出適用於 ElasticLoadBalancingV2 的所有可用接聽程式政策。**  

```
Get-ELB2SSLPolicy
```
**輸出：**  

```
Ciphers                                                                                                           Name                                  SslProtocols
-------                                                                                                           ----                                  ------------
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-2016-08             {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-2-2017-01     {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-1-2017-01     {TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-2-Ext-2018-06 {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-2018-06          {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-2015-05             {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-0-2015-04     {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-2-Res-2019-08  {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-1-2019-08      {TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-2-2019-08      {TLSv1.2}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSslPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2Tag`
<a name="elastic-load-balancing-v2_DescribeTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2Tag`。

**Tools for PowerShell V5**  
**範例 1：此範例列出指定資源的標籤。**  

```
Get-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**輸出：**  

```
ResourceArn                                                                                    Tags
-----------                                                                                    ----
arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f {stage, internalName, version}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DescribeTargetGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2TargetGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定的目標群組。**  

```
Get-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**輸出：**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 30
HealthCheckPath            : /
HealthCheckPort            : traffic-port
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 5
LoadBalancerArns           : {arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970
TargetGroupName            : test-tg
TargetType                 : instance
UnhealthyThresholdCount    : 2
VpcId                      : vpc-2cfd7000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTargetGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_DescribeTargetGroupAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2TargetGroupAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例描述指定之目標群組的屬性。**  

```
Get-ELB2TargetGroupAttribute -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**輸出：**  

```
Key                                   Value
---                                   -----
stickiness.enabled                    false
deregistration_delay.timeout_seconds  300
stickiness.type                       lb_cookie
stickiness.lb_cookie.duration_seconds 86400
slow_start.duration_seconds           0
load_balancing.algorithm.type         round_robin
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ELB2TargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ELB2TargetHealth`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回指定之目標群組中存在的目標運作狀態。**  

```
Get-ELB2TargetHealth -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**輸出：**  

```
HealthCheckPort Target                                                TargetHealth
--------------- ------                                                ------------
80              Amazon.ElasticLoadBalancingV2.Model.TargetDescription Amazon.ElasticLoadBalancingV2.Model.TargetHealth
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTargetHealth](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELB2Listener`
<a name="elastic-load-balancing-v2_CreateListener_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELB2Listener`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用預設動作 'Forward' 建立新的 ALB 接聽程式，將流量傳送至指定的目標群組。**  

```
$defaultAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{
  ForwardConfig = @{
    TargetGroups = @(
      @{ TargetGroupArn = "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testAlbTG/3d61c2f20aa5bccb" }
    )
    TargetGroupStickinessConfig = @{
      DurationSeconds = 900
      Enabled = $true
    }
  }
  Type = "Forward"
}

New-ELB2Listener -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676' -Port 8001 -Protocol "HTTP" -DefaultAction $defaultAction
```
**輸出：**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/1c84f02aec143e80
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676
Port            : 8001
Protocol        : HTTP
SslPolicy       :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateListener](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELB2LoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例使用兩個子網路建立對網際網路提供服務的新 Application Load Balancer。**  

```
New-ELB2LoadBalancer -Type application -Scheme internet-facing -IpAddressType ipv4 -Name 'New-Test-ALB' -SecurityGroup 'sg-07c3414abb8811cbd' -subnet 'subnet-c37a67a6','subnet-fc02eea0'
```
**輸出：**  

```
AvailabilityZones     : {us-east-1b, us-east-1a}
CanonicalHostedZoneId : Z35SXDOTRQ7X7K
CreatedTime           : 12/28/19 2:58:03 PM
DNSName               : New-Test-ALB-1391502222.us-east-1.elb.amazonaws.com
IpAddressType         : ipv4
LoadBalancerArn       : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/New-Test-ALB/dab2e4d90eb51493
LoadBalancerName      : New-Test-ALB
Scheme                : internet-facing
SecurityGroups        : {sg-07c3414abb8811cbd}
State                 : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState
Type                  : application
VpcId                 : vpc-2cfd7000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELB2Rule`
<a name="elastic-load-balancing-v2_CreateRule_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELB2Rule`。

**Tools for PowerShell V5**  
**範例 1：此範例會根據指定接聽程式的客戶標頭值，使用固定回應動作建立新接聽程式規則。**  

```
$newRuleAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{           
  "FixedResponseConfig" = @{
    "ContentType" = "text/plain"
    "MessageBody" = "Hello World"
    "StatusCode" = "200"
  }
  "Type" = [Amazon.ElasticLoadBalancingV2.ActionTypeEnum]::FixedResponse
}

$newRuleCondition = [Amazon.ElasticLoadBalancingV2.Model.RuleCondition]@{
  "httpHeaderConfig" = @{
    "HttpHeaderName" = "customHeader"
    "Values" = "header2","header1" 
  }         
  "Field" = "http-header"
}

New-ELB2Rule -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/1c84f02aec143e80' -Action $newRuleAction -Condition $newRuleCondition -Priority 10
```
**輸出：**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 10
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateRule](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ELB2TargetGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用提供的參數，建立新的目標群組。**  

```
New-ELB2TargetGroup -HealthCheckEnabled 1 -HealthCheckIntervalSeconds 30 -HealthCheckPath '/index.html' -HealthCheckPort 80 -HealthCheckTimeoutSecond 5 -HealthyThresholdCount 2 -UnhealthyThresholdCount 5 -Port 80 -Protocol 'HTTP' -TargetType instance -VpcId 'vpc-2cfd7000' -Name 'NewTargetGroup'
```
**輸出：**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 30
HealthCheckPath            : /index.html
HealthCheckPort            : 80
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 2
LoadBalancerArns           : {}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/NewTargetGroup/534e484681d801bf
TargetGroupName            : NewTargetGroup
TargetType                 : instance
UnhealthyThresholdCount    : 5
VpcId                      : vpc-2cfd7000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-ELB2Target`
<a name="elastic-load-balancing-v2_RegisterTargets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-ELB2Target`。

**Tools for PowerShell V5**  
**範例 1：此範例會向指定的目標群組註冊 'i-0672a4c4cdeae3111' 執行個體。**  

```
Register-ELB2Target -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -Target @{Port = 80; Id = 'i-0672a4c4cdeae3111'}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterTargets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELB2Listener`
<a name="elastic-load-balancing-v2_DeleteListener_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELB2Listener`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的接聽程式。**  

```
Remove-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Listener (DeleteListener)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
**範例 2：此範例會從負載平衡器移除指定的接聽程式。**  

```
Remove-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Listener (DeleteListener)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteListener](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_RemoveListenerCertificates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELB2ListenerCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的目標群組移除指定的憑證。**  

```
Remove-ELB2ListenerCertificate -Certificate @{CertificateArn = 'arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97'} -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2ListenerCertificate (RemoveListenerCertificates)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELB2LoadBalancer`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的負載平衡器。**  

```
Remove-ELB2LoadBalancer -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2LoadBalancer (DeleteLoadBalancer)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELB2Rule`
<a name="elastic-load-balancing-v2_DeleteRule_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELB2Rule`。

**Tools for PowerShell V5**  
**範例 1：此範例會從接聽程式移除指定的規則**  

```
Remove-ELB2Rule -RuleArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/3873f123b98f7618/4b25eb10a42e33ab'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Rule (DeleteRule)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/3873f123b98f7618/4b25eb10a42e33ab".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteRule](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELB2Tag`
<a name="elastic-load-balancing-v2_RemoveTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELB2Tag`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除指定索引鍵的標籤。**  

```
Remove-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -TagKey 'productVersion'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Tag (RemoveTags)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-ELB2TargetGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除指定的目標群組。**  

```
Remove-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testsssss/4e0b6076bc6483a7'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2TargetGroup (DeleteTargetGroup)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testsssss/4e0b6076bc6483a7".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELB2IpAddressType`
<a name="elastic-load-balancing-v2_SetIpAddressType_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELB2IpAddressType`。

**Tools for PowerShell V5**  
**範例 1：此範例會將負載平衡器 IP 位址類型從 'IPv4' 變更為 'DualStack'。**  

```
Set-ELB2IpAddressType -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -IpAddressType dualstack
```
**輸出：**  

```
Value
-----
dualstack
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetIpAddressType](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELB2RulePriority`
<a name="elastic-load-balancing-v2_SetRulePriorities_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELB2RulePriority`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更指定接聽程式規則的優先順序。**  

```
Set-ELB2RulePriority -RulePriority -RulePriority @{Priority = 11; RuleArn = 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/a4eb199fa5046f80/dbf4c6dcef3ec6f8'}
```
**輸出：**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 11
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/a4eb199fa5046f80/dbf4c6dcef3ec6f8
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetRulePriorities](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELB2SecurityGroup`
<a name="elastic-load-balancing-v2_SetSecurityGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELB2SecurityGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會將安全群組 'sg-07c3414abb8811cbd' 新增至指定的負載平衡器。**  

```
Set-ELB2SecurityGroup -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -SecurityGroup 'sg-07c3414abb8811cbd'
```
**輸出：**  

```
sg-07c3414abb8811cbd
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-ELB2Subnet`
<a name="elastic-load-balancing-v2_SetSubnets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-ELB2Subnet`。

**Tools for PowerShell V5**  
**範例 1：此範例會修改指定負載平衡器的子網路。**  

```
Set-ELB2Subnet -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Subnet 'subnet-7d8a0a51','subnet-c37a67a6'
```
**輸出：**  

```
LoadBalancerAddresses SubnetId        ZoneName
--------------------- --------        --------
{}                    subnet-7d8a0a51 us-east-1c
{}                    subnet-c37a67a6 us-east-1b
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetSubnets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-ELB2Target`
<a name="elastic-load-balancing-v2_DeregisterTargets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-ELB2Target`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的目標群組取消註冊執行個體 'i-0672a4c4cdeae3111'。**  

```
$targetDescription = New-Object Amazon.ElasticLoadBalancingV2.Model.TargetDescription
$targetDescription.Id = 'i-0672a4c4cdeae3111'
Unregister-ELB2Target -Target $targetDescription -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterTargets](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon FSx 範例
<a name="powershell_fsx_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon FSx 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-FSXResourceTag`
<a name="fsx_TagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-FSXResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將標籤新增至給定的資源。**  

```
Add-FSXResourceTag -ResourceARN "arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a" -Tag @{Key="Users";Value="Test"}
```
**輸出：**  

```
arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-FSXBackup`
<a name="fsx_DescribeBackups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-FSXBackup`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取自昨天以來，為給定檔案系統 ID 建立的備份。**  

```
Get-FSXBackup -Filter @{Name="file-system-id";Values=$fsx.FileSystemId} | Where-Object CreationTime -gt (Get-Date).AddDays(-1)
```
**輸出：**  

```
BackupId        : backup-01dac234e56782bcc
CreationTime    : 6/14/2019 3:35:14 AM
FailureDetails  :
FileSystem      : Amazon.FSx.Model.FileSystem
KmsKeyId        : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f1-e1234c5af123
Lifecycle       : AVAILABLE
ProgressPercent : 100
ResourceARN     : arn:aws:fsx:eu-west-1:123456789012:backup/backup-01dac234e56782bcc
Tags            : {}
Type            : AUTOMATIC
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeBackups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-FSXFileSystem`
<a name="fsx_DescribeFileSystems_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-FSXFileSystem`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回給定 filesystemId 的描述。**  

```
Get-FSXFileSystem -FileSystemId fs-01cd23bc4bdf5678a
```
**輸出：**  

```
CreationTime         : 1/17/2019 9:55:30 AM
DNSName              : fs-01cd23bc4bdf5678a.ktmsad.local
FailureDetails       :
FileSystemId         : fs-01cd23bc4bdf5678a
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-5b67-8bde-a9f0-e1234c5af678
Lifecycle            : AVAILABLE
LustreConfiguration  :
NetworkInterfaceIds  : {eni-07d1dda1322b7e209}
OwnerId              : 123456789012
ResourceARN          : arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a
StorageCapacity      : 300
SubnetIds            : {subnet-7d123456}
Tags                 : {FSx-Service}
VpcId                : vpc-41cf2b3f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeFileSystems](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-FSXResourceTagList`
<a name="fsx_ListTagsForResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-FSXResourceTagList`。

**Tools for PowerShell V5**  
**範例 1：此範例會列出所提供資源 arn 的標籤。**  

```
Get-FSXResourceTagList -ResourceARN $fsx.ResourceARN
```
**輸出：**  

```
Key         Value
---         -----
FSx-Service Windows
Users       Dev
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-FSXBackup`
<a name="fsx_CreateBackup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-FSXBackup`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立給定檔案系統的備份。**  

```
New-FSXBackup -FileSystemId fs-0b1fac2345623456ba
```
**輸出：**  

```
BackupId        : backup-0b1fac2345623456ba
CreationTime    : 6/14/2019 5:37:17 PM
FailureDetails  :
FileSystem      : Amazon.FSx.Model.FileSystem
KmsKeyId        : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f3-e1234c5af678
Lifecycle       : CREATING
ProgressPercent : 0
ResourceARN     : arn:aws:fsx:eu-west-1:123456789012:backup/backup-0b1fac2345623456ba
Tags            : {}
Type            : USER_INITIATED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateBackup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-FSXFileSystem`
<a name="fsx_CreateFileSystem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-FSXFileSystem`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的 300GB Windows 檔案系統，允許從指定子網路存取，該存取支援每秒高達 8 MB 的輸送量。新的檔案系統會自動加入指定的 Microsoft Active Directory。**  

```
New-FSXFileSystem -FileSystemType WINDOWS -StorageCapacity 300 -SubnetId subnet-1a2b3c4d5e6f -WindowsConfiguration @{ThroughputCapacity=8;ActiveDirectoryId='d-1a2b3c4d'}
```
**輸出：**  

```
CreationTime         : 12/10/2018 6:06:59 PM
DNSName              : fs-abcdef01234567890.example.com
FailureDetails       :
FileSystemId         : fs-abcdef01234567890
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:us-west-2:123456789012:key/a1234567-252c-45e9-afaa-123456789abc
Lifecycle            : CREATING
LustreConfiguration  :
NetworkInterfaceIds  : {}
OwnerId              : 123456789012
ResourceARN          : arn:aws:fsx:us-west-2:123456789012:file-system/fs-abcdef01234567890
StorageCapacity      : 300
SubnetIds            : {subnet-1a2b3c4d5e6f}
Tags                 : {}
VpcId                : vpc-1a2b3c4d5e6f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-FSXFileSystemFromBackup`
<a name="fsx_CreateFileSystemFromBackup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-FSXFileSystemFromBackup`。

**Tools for PowerShell V5**  
**範例 1：此範例會從現有的 Amazon FSx for Windows File Server 備份，建立新的 Amazon FSx 檔案系統。**  

```
New-FSXFileSystemFromBackup -BackupId $backupID -Tag @{Key="tag:Name";Value="from-manual-backup"} -SubnetId $SubnetID -SecurityGroupId $SG_ID -WindowsConfiguration @{ThroughputCapacity=8;ActiveDirectoryId=$DirectoryID}
```
**輸出：**  

```
CreationTime         : 8/8/2019 12:59:58 PM
DNSName              : fs-012ff34e56789120.ktmsad.local
FailureDetails       :
FileSystemId         : fs-012ff34e56789120
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-5b67-1bde-a2f3-e4567c8a9321
Lifecycle            : CREATING
LustreConfiguration  :
NetworkInterfaceIds  : {}
OwnerId              : 933303704102
ResourceARN          : arn:aws:fsx:eu-west-1:123456789012:file-system/fs-012ff34e56789120
StorageCapacity      : 300
SubnetIds            : {subnet-fa1ae23c}
Tags                 : {tag:Name}
VpcId                : vpc-12cf3b4f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateFileSystemFromBackup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-FSXBackup`
<a name="fsx_DeleteBackup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-FSXBackup`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除給定的 backup-id。**  

```
Remove-FSXBackup -BackupId $backupID
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXBackup (DeleteBackup)" on target "backup-0bbca1e2345678e12".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

BackupId                 Lifecycle
--------                 ---------
backup-0bbca1e2345678e12 DELETED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBackup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-FSXFileSystem`
<a name="fsx_DeleteFileSystem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-FSXFileSystem`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除給定的 FSX 檔案系統 ID。**  

```
Remove-FSXFileSystem -FileSystemId fs-012ff34e567890120
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXFileSystem (DeleteFileSystem)" on target "fs-012ff34e567890120".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

FileSystemId         Lifecycle WindowsResponse
------------         --------- ---------------
fs-012ff34e567890120 DELETING  Amazon.FSx.Model.DeleteFileSystemWindowsResponse
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-FSXResourceTag`
<a name="fsx_UntagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-FSXResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除給定 FSX 檔案系統資源 ARN 的資源標籤。**  

```
Remove-FSXResourceTag -ResourceARN $FSX.ResourceARN -TagKey Users
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXResourceTag (UntagResource)" on target "arn:aws:fsx:eu-west-1:933303704102:file-system/fs-07cd45bc6bdf2674a".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-FSXFileSystem`
<a name="fsx_UpdateFileSystem_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-FSXFileSystem`。

**Tools for PowerShell V5**  
**範例 1：此範例會透過 UpdateFileSystemWindowsConfiguration，更新 FSX 檔案系統自動備份保留天數。**  

```
$UpdateFSXWinConfig = [Amazon.FSx.Model.UpdateFileSystemWindowsConfiguration]::new()
	$UpdateFSXWinConfig.AutomaticBackupRetentionDays = 35
	Update-FSXFileSystem -FileSystemId $FSX.FileSystemId -WindowsConfiguration $UpdateFSXWinConfig
```
**輸出：**  

```
CreationTime         : 1/17/2019 9:55:30 AM
DNSName              : fs-01cd23bc4bdf5678a.ktmsad.local
FailureDetails       :
FileSystemId         : fs-01cd23bc4bdf5678a
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f2-e1234c5af678
Lifecycle            : AVAILABLE
LustreConfiguration  :
NetworkInterfaceIds  : {eni-01cd23bc4bdf5678a}
OwnerId              : 933303704102
ResourceARN          : arn:aws:fsx:eu-west-1:933303704102:file-system/fs-07cd45bc6bdf2674a
StorageCapacity      : 300
SubnetIds            : {subnet-1d234567}
Tags                 : {FSx-Service}
VpcId                : vpc-23cf4b5f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon Glacier 範例
<a name="powershell_glacier_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon Glacier 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-GLCJob`
<a name="glacier_DescribeJob_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-GLCJob`。

**Tools for PowerShell V5**  
**範例 1：傳回指定任務的詳細資訊。當任務成功完成時，可使用 Read-GCJobOutput cmdlet 將任務的內容 (封存或庫存清單) 擷取至本機檔案系統。**  

```
Get-GLCJob -VaultName myvault -JobId "op1x...JSbthM"
```
**輸出：**  

```
Action                       : ArchiveRetrieval
ArchiveId                    : o9O9j...X-TpIhQJw
ArchiveSHA256TreeHash        : 79f3ea754c02f58...dc57bf4395b
ArchiveSizeInBytes           : 38034480
Completed                    : False
CompletionDate               : 1/1/0001 12:00:00 AM
CreationDate                 : 12/13/2018 11:00:14 AM
InventoryRetrievalParameters :
InventorySizeInBytes         : 0
JobDescription               :
JobId                        : op1x...JSbthM
JobOutputPath                :
OutputLocation               :
RetrievalByteRange           : 0-38034479
SelectParameters             :
SHA256TreeHash               : 79f3ea754c02f58...dc57bf4395b
SNSTopic                     :
StatusCode                   : InProgress
StatusMessage                :
Tier                         : Standard
VaultARN                     : arn:aws:glacier:us-west-2:012345678912:vaults/test
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeJob](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-GLCVault`
<a name="glacier_CreateVault_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-GLCVault`。

**Tools for PowerShell V5**  
**範例 1：為使用者帳戶建立新的保存庫。由於未將任何值提供給 -AccountId 參數，Cmdlet 會使用預設值 "-" 來表示目前的帳戶。**  

```
New-GLCVault -VaultName myvault
```
**輸出：**  

```
/01234567812/vaults/myvault
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVault](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Read-GLCJobOutput`
<a name="glacier_GetJobOutput_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Read-GLCJobOutput`。

**Tools for PowerShell V5**  
**範例 1：下載排程於指定任務中擷取的封存內容，並將內容存放在磁碟上的檔案中。如果有的話，下載會為您驗證檢查總和。如果需要，可以透過指定 `-Select '*'` 傳回包含檢查總和的整體回應。**  

```
Read-GLCJobOutput -VaultName myvault -JobId "HSWjArc...Zq2XLiW" -FilePath "c:\temp\blue.bin"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetJobOutput](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-GLCJob`
<a name="glacier_InitiateJob_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-GLCJob`。

**Tools for PowerShell V5**  
**範例 1：啟動任務，從使用者擁有的指定保存庫擷取封存。您可以使用 Get-GLCJob cmdlet 檢查任務的狀態。當任務成功完成時，可使用 Read-GCJobOutput cmdlet 將封存的內容擷取至本機檔案系統。**  

```
Start-GLCJob -VaultName myvault -JobType "archive-retrieval" -JobDescription "archive retrieval" -ArchiveId "o9O9j...TX-TpIhQJw"
```
**輸出：**  

```
JobId            JobOutputPath Location
-----            ------------- --------
op1x...JSbthM                  /012345678912/vaults/test/jobs/op1xe...I4HqCHkSJSbthM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [InitiateJob](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-GLCArchive`
<a name="glacier_UploadArchive_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-GLCArchive`。

**Tools for PowerShell V5**  
**範例 1：將單一檔案上傳到指定的保存庫，傳回封存 ID 和運算的檢查總和。**  

```
Write-GLCArchive -VaultName myvault -FilePath c:\temp\blue.bin
```
**輸出：**  

```
FilePath                    ArchiveId              Checksum
--------                    ---------              --------
C:\temp\blue.bin            o9O9jUUs...TTX-TpIhQJw 79f3e...f4395b
```
**範例 2：將資料夾階層的內容，上傳至使用者帳戶中指定的保存庫。對於每個上傳的檔案，Cmdlet 會發出檔案名稱、對應的封存 ID 和封存的運算檢查總和。**  

```
Write-GLCArchive -VaultName myvault -FolderPath . -Recurse
```
**輸出：**  

```
FilePath                    ArchiveId              Checksum
--------                    ---------              --------
C:\temp\blue.bin            o9O9jUUs...TTX-TpIhQJw 79f3e...f4395b
C:\temp\green.bin           qXAfOdSG...czo729UHXrw d50a1...9184b9
C:\temp\lum.bin             39aNifP3...q9nb8nZkFIg 28886...5c3e27
C:\temp\red.bin             vp7E6rU_...Ejk_HhjAxKA e05f7...4e34f5
C:\temp\Folder1\file1.txt   _eRINlip...5Sxy7dD2BaA d0d2a...c8a3ba
C:\temp\Folder2\file2.iso   -Ix3jlmu...iXiDh-XfOPA 7469e...3e86f1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**的 [UploadArchive](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS Glue 使用 Tools for PowerShell V5 的範例
<a name="powershell_glue_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS Glue。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `New-GLUEJob`
<a name="glue_CreateJob_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-GLUEJob`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 Glue AWS 中建立新的任務。命令名稱值一律為 `glueetl`. AWS Glue，支援執行以 Python 或 Scala 撰寫的任務指令碼。在此範例中，任務指令碼 (MyTestGlueJob.py) 以 Python 撰寫。Python 參數在 `$DefArgs` 變數中指定，然後在 `DefaultArguments` 參數中傳遞至 PowerShell 命令，該命令接受雜湊表。`$JobParams`變數中的參數來自 CreateJob API，記錄在 Glue API 參考的任務 (https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html：//) AWS 主題中。**  

```
$Command = New-Object Amazon.Glue.Model.JobCommand
$Command.Name = 'glueetl'
$Command.ScriptLocation = 's3://amzn-s3-demo-source-bucket/admin/MyTestGlueJob.py'
$Command

$Source = "source_test_table"
$Target = "target_test_table"
$Connections = $Source, $Target

$DefArgs = @{
     '--TempDir' = 's3://amzn-s3-demo-bucket/admin'
     '--job-bookmark-option' = 'job-bookmark-disable'
     '--job-language' = 'python'
     }
$DefArgs

$ExecutionProp = New-Object Amazon.Glue.Model.ExecutionProperty
$ExecutionProp.MaxConcurrentRuns = 1
$ExecutionProp

$JobParams = @{
    "AllocatedCapacity"    = "5"
    "Command"              = $Command
    "Connections_Connection" = $Connections
    "DefaultArguments"  = $DefArgs
    "Description"       = "This is a test"
    "ExecutionProperty" = $ExecutionProp
    "MaxRetries"        = "1"
    "Name"              = "MyOregonTestGlueJob"
    "Role"              = "Amazon-GlueServiceRoleForSSM"
    "Timeout"           = "20"
     }

New-GlueJob @JobParams
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateJob](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS Health 使用 Tools for PowerShell V5 的範例
<a name="powershell_health_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS Health。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-HLTHEvent`
<a name="health_DescribeEvents_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-HLTHEvent`。

**Tools for PowerShell V5**  
**範例 1：此命令會從 AWS 個人運作狀態儀表板傳回事件。使用者新增 -Region 參數，以查看美國東部 (維吉尼亞北部) 區域中可用於服務的事件，但 -Filter\$1Region 參數會篩選出在歐盟 (倫敦) 和美國西部 (奧勒岡) 區域 (eu-west-2 和 us-west-2) 記錄的事件。-Filter\$1StartTime 參數篩選事件可以開始的時間範圍，而 -Filter\$1EndTime 參數篩選事件可以結束的時間範圍。結果是 RDS 的排程維護事件，其會在指定的 -Filter\$1StartTime 範圍內開始，並在排定的 -Filter\$1EndTime 範圍內結束。**  

```
Get-HLTHEvent -Region us-east-1 -Filter_Region "eu-west-2","us-west-2" -Filter_StartTime @{from="3/14/2019 6:30:00AM";to="3/15/2019 5:00:00PM"} -Filter_EndTime @{from="3/21/2019 7:00:00AM";to="3/21/2019 5:00:00PM"}
```
**輸出：**  

```
Arn               : arn:aws:health:us-west-2::event/RDS/AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED/AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED_USW2_20190314_20190321
AvailabilityZone  : 
EndTime           : 3/21/2019 2:00:00 PM
EventTypeCategory : scheduledChange
EventTypeCode     : AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED
LastUpdatedTime   : 2/28/2019 2:26:07 PM
Region            : us-west-2
Service           : RDS
StartTime         : 3/14/2019 2:00:00 PM
StatusCode        : open
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEvents](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 IAM 範例
<a name="powershell_iam_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 IAM 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-IAMClientIDToOpenIDConnectProvider`
<a name="iam_AddClientIdToOpenIdConnectProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-IAMClientIDToOpenIDConnectProvider`。

**Tools for PowerShell V5**  
**範例 1：此命令會將用戶端 ID (或對象) `my-application-ID` 新增至名為 `server.example.com` 的現有 OIDC 提供者。**  

```
Add-IAMClientIDToOpenIDConnectProvider -ClientID "my-application-ID" -OpenIDConnectProviderARN "arn:aws:iam::123456789012:oidc-provider/server.example.com"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddClientIdToOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-IAMRoleTag`
<a name="iam_TagRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-IAMRoleTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會標籤新增至 Identity Management Service 中的角色**  

```
Add-IAMRoleTag -RoleName AdminRoleacess -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-IAMRoleToInstanceProfile`
<a name="iam_AddRoleToInstanceProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-IAMRoleToInstanceProfile`。

**Tools for PowerShell V5**  
**範例 1：此命令會將名為 `S3Access` 的角色新增至名為 `webserver` 的現有執行個體設定檔。若要建立執行個體設定檔，請使用 `New-IAMInstanceProfile` 命令。使用此命令建立執行個體設定檔並將其與角色關聯起來之後，可以將其連接至 EC2 執行個體。為此，請使用 `New-EC2Instance` cmdlet 搭配 `InstanceProfile_Arn` 或 `InstanceProfile-Name` 參數啟動新的執行個體。**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddRoleToInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-IAMUserTag`
<a name="iam_TagUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-IAMUserTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會標籤新增至 Identity Management Service 中的使用者**  

```
Add-IAMUserTag -UserName joe -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-IAMUserToGroup`
<a name="iam_AddUserToGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-IAMUserToGroup`。

**Tools for PowerShell V5**  
**範例 1：此命令會將名為 `Bob` 的使用者新增至名為 `Admins` 的群組。**  

```
Add-IAMUserToGroup -UserName "Bob" -GroupName "Admins"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddUserToGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-IAMMFADevice`
<a name="iam_DeactivateMfaDevice_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Disable-IAMMFADevice`。

**Tools for PowerShell V5**  
**範例 1：此命令會停用與序號為 `123456789012` 的使用者 `Bob` 關聯的硬體 MFA 裝置。**  

```
Disable-IAMMFADevice -UserName "Bob" -SerialNumber "123456789012"
```
**範例 2：此命令會停用與 ARN 為 `arn:aws:iam::210987654321:mfa/David` 的使用者 `David` 關聯的虛擬 MFA 裝置。請注意，虛擬 MFA 裝置不會從帳戶中刪除。虛擬裝置仍然存在，並顯示在 `Get-IAMVirtualMFADevice` 命令的輸出中。必須先使用 `Remove-IAMVirtualMFADevice` 命令刪除舊的虛擬 MFA 裝置，才能為同一使用者建立新裝置。**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeactivateMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-IAMPassword`
<a name="iam_ChangePassword_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-IAMPassword`。

**Tools for PowerShell V5**  
**範例 1：此命令會變更執行命令的使用者密碼。此命令只能由 IAM 使用者呼叫。如果您在使用 AWS 帳戶 （根） 登入資料登入時呼叫此命令，命令會傳回`InvalidUserType`錯誤。**  

```
Edit-IAMPassword -OldPassword "MyOldP@ssw0rd" -NewPassword "MyNewP@ssw0rd"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ChangePassword](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-IAMMFADevice`
<a name="iam_EnableMfaDevice_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Enable-IAMMFADevice`。

**Tools for PowerShell V5**  
**範例 1：此命令會啟用序號為 `987654321098` 的硬體 MFA 裝置，並將裝置與使用者 `Bob` 關聯起來。它包含裝置中依序排列的前兩個代碼。**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**範例 2：此範例會建立並啟用虛擬 MFA 裝置。第一個命令會建立虛擬裝置，並在變數 `$MFADevice` 中傳回裝置的物件表示。可以使用 `.Base32StringSeed` 或 `QRCodePng` 屬性來設定使用者的軟體應用程式。最後一個命令會將裝置指派給使用者 `David`，依裝置序號標識裝置。命令也會依序包含來自虛擬 MFA 裝置的前兩個代碼， AWS 以將裝置與 同步。**  

```
$MFADevice = New-IAMVirtualMFADevice -VirtualMFADeviceName "MyMFADevice"
# see example for New-IAMVirtualMFADevice to see how to configure the software program with PNG or base32 seed code
Enable-IAMMFADevice -UserName "David" -SerialNumber -SerialNumber $MFADevice.SerialNumber -AuthenticationCode1 "24681357" -AuthenticationCode2 "13572468"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [EnableMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAccessKey`
<a name="iam_ListAccessKeys_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAccessKey`。

**Tools for PowerShell V5**  
**範例 1：此命令會列出名為 `Bob` 之 IAM 使用者的存取金鑰。請注意，IAM 使用者的私密存取金鑰無法列出。如果私密存取金鑰遺失，必須使用 `New-IAMAccessKey` cmdlet 建立新的存取金鑰。**  

```
Get-IAMAccessKey -UserName "Bob"
```
**輸出：**  

```
AccessKeyId                CreateDate                   Status              UserName
-----------                ----------                   ------              --------
AKIAIOSFODNN7EXAMPLE       12/3/2014 10:53:41 AM        Active              Bob
AKIAI44QH8DHBEXAMPLE       6/6/2013 8:42:26 PM          Inactive            Bob
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAccessKeys](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAccessKeyLastUsed`。

**Tools for PowerShell V5**  
**範例 1：傳回所提供存取金鑰的擁有使用者名稱和上次使用資訊。**  

```
Get-IAMAccessKeyLastUsed -AccessKeyId ABCDEXAMPLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAccessKeyLastUsed](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAccountAlias`
<a name="iam_ListAccountAliases_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAccountAlias`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回 AWS 帳戶的帳戶別名。**  

```
Get-IAMAccountAlias
```
**輸出：**  

```
ExampleCo
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAccountAliases](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAccountAuthorizationDetail`
<a name="iam_GetAccountAuthorizationDetails_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAccountAuthorizationDetail`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得 AWS 帳戶中身分的授權詳細資訊，並顯示傳回物件的元素清單，包括使用者、群組和角色。例如，`UserDetailList` 屬性會顯示使用者的詳細資訊。`RoleDetailList` 和 `GroupDetailList` 屬性提供類似的資訊。**  

```
$Details=Get-IAMAccountAuthorizationDetail
$Details
```
**輸出：**  

```
GroupDetailList : {Administrators, Developers, Testers, Backup}
IsTruncated     : False
Marker          : 
RoleDetailList  : {TestRole1, AdminRole, TesterRole, clirole...}
UserDetailList  : {Administrator, Bob, BackupToS3, }
```

```
$Details.UserDetailList
```
**輸出：**  

```
Arn            : arn:aws:iam::123456789012:user/Administrator
CreateDate     : 10/16/2014 9:03:09 AM
GroupList      : {Administrators}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE1
UserName       : Administrator
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/Bob
CreateDate     : 4/6/2015 12:54:42 PM
GroupList      : {Developers}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE2
UserName       : bab
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/BackupToS3
CreateDate     : 1/27/2015 10:15:08 AM
GroupList      : {Backup}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE3
UserName       : BackupToS3
UserPolicyList : {BackupServicePermissionsToS3Buckets}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAccountAuthorizationDetails](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAccountPasswordPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回目前帳戶之密碼政策的詳細資訊。如果沒有為帳戶定義密碼政策，命令會傳回 `NoSuchEntity` 錯誤。**  

```
Get-IAMAccountPasswordPolicy
```
**輸出：**  

```
AllowUsersToChangePassword : True
ExpirePasswords            : True
HardExpiry                 : False
MaxPasswordAge             : 90
MinimumPasswordLength      : 8
PasswordReusePrevention    : 20
RequireLowercaseCharacters : True
RequireNumbers             : True
RequireSymbols             : False
RequireUppercaseCharacters : True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAccountSummary`
<a name="iam_GetAccountSummary_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAccountSummary`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 AWS 帳戶中目前 IAM 實體用量和目前 IAM 實體配額的相關資訊。**  

```
Get-IAMAccountSummary
```
**輸出：**  

```
Key                                        Value
Users                                      7
GroupPolicySizeQuota                       5120
PolicyVersionsInUseQuota                   10000
ServerCertificatesQuota                    20
AccountSigningCertificatesPresent          0
AccountAccessKeysPresent                   0
Groups                                     3
UsersQuota                                 5000
RolePolicySizeQuota                        10240
UserPolicySizeQuota                        2048
GroupsPerUserQuota                         10
AssumeRolePolicySizeQuota                  2048
AttachedPoliciesPerGroupQuota              2
Roles                                      9
VersionsPerPolicyQuota                     5
GroupsQuota                                100
PolicySizeQuota                            5120
Policies                                   5
RolesQuota                                 250
ServerCertificates                         0
AttachedPoliciesPerRoleQuota               2
MFADevicesInUse                            2
PoliciesQuota                              1000
AccountMFAEnabled                          1
Providers                                  2
InstanceProfilesQuota                      100
MFADevices                                 4
AccessKeysPerUserQuota                     2
AttachedPoliciesPerUserQuota               2
SigningCertificatesPerUserQuota            2
PolicyVersionsInUse                        4
InstanceProfiles                           1
...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAccountSummary](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAttachedGroupPolicyList`
<a name="iam_ListAttachedGroupPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAttachedGroupPolicyList`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回連接到`Admins` AWS 帳戶中名為 之 IAM 群組的受管政策的名稱和 ARNs。若要查看內嵌在群組中的內嵌政策的清單，請使用 `Get-IAMGroupPolicyList` 命令。**  

```
Get-IAMAttachedGroupPolicyList -GroupName "Admins"
```
**輸出：**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
arn:aws:iam::aws:policy/AdministratorAccess               AdministratorAccess
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAttachedGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAttachedRolePolicyList`
<a name="iam_ListAttachedRolePolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAttachedRolePolicyList`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回連接至 AWS 帳戶中名為 `SecurityAuditRole` 之 IAM 角色的受管政策的名稱和 ARN。若要查看內嵌在角色中的內嵌政策清單，請使用 `Get-IAMRolePolicyList` 命令。**  

```
Get-IAMAttachedRolePolicyList -RoleName "SecurityAuditRole"
```
**輸出：**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAttachedRolePolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMAttachedUserPolicyList`
<a name="iam_ListAttachedUserPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMAttachedUserPolicyList`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回`Bob` AWS 帳戶中名為 之 IAM 使用者之受管政策的名稱和 ARNs。若要查看內嵌在 IAM 使用者中的內嵌政策的清單，請使用 `Get-IAMUserPolicyList` 命令。**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**輸出：**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAttachedUserPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMContextKeysForCustomPolicy`
<a name="iam_GetContextKeysForCustomPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMContextKeysForCustomPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取所提供政策 json 中的所有內容索引鍵。若要提供多個政策，可以採用以逗號分隔的值清單形式提供。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForCustomPolicy -PolicyInputList $policy1,$policy2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetContextKeysForCustomPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMContextKeysForPrincipalPolicy`
<a name="iam_GetContextKeysForPrincipalPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMContextKeysForPrincipalPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取所提供政策 json 中的所有內容索引鍵，以及連接至 IAM 實體 (使用者/角色等) 的政策。對於 -PolicyInputList，您可以提供包含多個以逗號分隔的值的清單。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForPrincipalPolicy -PolicyInputList $policy1,$policy2 -PolicySourceArn arn:aws:iam::852640994763:user/TestUser
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMCredentialReport`
<a name="iam_GetCredentialReport_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMCredentialReport`。

**Tools for PowerShell V5**  
**範例 1：此範例會開啟傳回的報告，並以文字行陣列的形式將其輸出至管道。第一行是帶有以逗號分隔的資料欄名稱的標題。每個連續資料列是一個使用者的詳細資訊列，每個欄位以逗號分隔。必須先使用 `Request-IAMCredentialReport` cmdlet 產生報告，然後才能檢視報告。若要以單一字串擷取報告，請使用 `-Raw`，勿用 `-AsTextArray`。`-AsTextArray` 交換器也接受別名 `-SplitLines`。如需輸出中資料欄的完整清單，請參閱服務 API 參考。請注意，如果不使用 `-AsTextArray` 或 `-SplitLines`，必須使用 .NET `StreamReader` 類從 `.Content` 屬性擷取文字。**  

```
Request-IAMCredentialReport
```
**輸出：**  

```
Description                                                         State
-----------                                                         -----
No report exists. Starting a new report generation task             STARTED
```

```
Get-IAMCredentialReport -AsTextArray
```
**輸出：**  

```
      user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_2_active,access_key_2_last_rotated,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated root_account,arn:aws:iam::123456789012:root,2014-10-15T16:31:25+00:00,not_supported,2015-04-20T17:41:10+00:00,not_supported,not_supported,true,false,N/A,false,N/A,false,N/A,false,N/A
Administrator,arn:aws:iam::123456789012:user/Administrator,2014-10-16T16:03:09+00:00,true,2015-04-20T15:18:32+00:00,2014-10-16T16:06:00+00:00,N/A,false,true,2014-12-03T18:53:41+00:00,true,2015-03-25T20:38:14+00:00,false,N/A,false,N/A
Bill,arn:aws:iam::123456789012:user/Bill,2015-04-15T18:27:44+00:00,false,N/A,N/A,N/A,false,false,N/A,false,N/A,false,2015-04-20T20:00:12+00:00,false,N/A
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetCredentialReport](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMEntitiesForPolicy`
<a name="iam_ListEntitiesForPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMEntitiesForPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回已連接政策 `arn:aws:iam::123456789012:policy/TestPolicy` 的 IAM 群組、角色和使用者的清單。**  

```
Get-IAMEntitiesForPolicy -PolicyArn "arn:aws:iam::123456789012:policy/TestPolicy"
```
**輸出：**  

```
IsTruncated  : False
Marker       : 
PolicyGroups : {}
PolicyRoles  : {testRole}
PolicyUsers  : {Bob, Theresa}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListEntitiesForPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMGroup`
<a name="iam_GetGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 IAM 群組 `Testers` 的詳細資訊，包括屬於該群組的所有 IAM 使用者的集合。**  

```
$results = Get-IAMGroup -GroupName "Testers"
$results
```
**輸出：**  

```
Group                                     IsTruncated           Marker                Users
-----                                     -----------           ------                -----
Amazon.IdentityManagement.Model.Group     False                                       {Theresa, David}
```

```
$results.Group
```
**輸出：**  

```
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : 3RHNZZGQJ7QHMAEXAMPLE1
GroupName  : Testers
Path       : /
```

```
$results.Users
```
**輸出：**  

```
Arn              : arn:aws:iam::123456789012:user/Theresa
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : 4OSVDDJJTF4XEEXAMPLE2
UserName         : Theresa

Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE3
UserName         : David
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMGroupForUser`
<a name="iam_ListGroupsForUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMGroupForUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 IAM 使用者 `David` 所屬之 IAM 群組的清單。**  

```
Get-IAMGroupForUser -UserName David
```
**輸出：**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE2
GroupName  : Testers
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE3
GroupName  : Developers
Path       : /
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListGroupsForUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMGroupList`
<a name="iam_ListGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMGroupList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回目前 中定義之所有 IAM 群組的集合 AWS 帳戶。**  

```
Get-IAMGroupList
```
**輸出：**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /

Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE2
GroupName  : Developers
Path       : /

Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE3
GroupName  : Testers
Path       : /
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMGroupPolicy`
<a name="iam_GetGroupPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMGroupPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回群組 `PowerUserAccess-Testers` 名為 `Testers` 的嵌入式內嵌政策的詳細資訊。`PolicyDocument` 屬性經過 URL 編碼。在此範例中，它會使用 `UrlDecode` .NET 方法解碼。**  

```
$results = Get-IAMGroupPolicy -GroupName Testers -PolicyName PowerUserAccess-Testers
$results
```
**輸出：**  

```
GroupName     PolicyDocument                                              PolicyName
---------     --------------                                              ----------
Testers       %7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0A%20... PowerUserAccess-Testers

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
  ]
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMGroupPolicyList`
<a name="iam_ListGroupPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMGroupPolicyList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回內嵌在群組 `Testers` 中的內嵌政策清單。若要取得連接到群組的受管政策，請使用 `Get-IAMAttachedGroupPolicyList` 命令。**  

```
Get-IAMGroupPolicyList -GroupName Testers
```
**輸出：**  

```
Deny-Assume-S3-Role-In-Production
PowerUserAccess-Testers
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMInstanceProfile`
<a name="iam_GetInstanceProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMInstanceProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回目前 AWS 帳戶中定義的名為 `ec2instancerole` 之執行個體描述檔的詳細資訊。**  

```
Get-IAMInstanceProfile -InstanceProfileName ec2instancerole
```
**輸出：**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMInstanceProfileForRole`
<a name="iam_ListInstanceProfilesForRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMInstanceProfileForRole`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回與角色 `ec2instancerole` 關聯之執行個體設定檔的詳細資訊。**  

```
Get-IAMInstanceProfileForRole -RoleName ec2instancerole
```
**輸出：**  

```
      Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
      CreateDate          : 2/17/2015 2:49:04 PM
      InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
      InstanceProfileName : ec2instancerole
      Path                : /
      Roles               : {ec2instancerole}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListInstanceProfilesForRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMInstanceProfileList`
<a name="iam_ListInstanceProfiles_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMInstanceProfileList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回目前 中定義的執行個體描述檔集合 AWS 帳戶。**  

```
Get-IAMInstanceProfileList
```
**輸出：**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListInstanceProfiles](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMLoginProfile`
<a name="iam_GetLoginProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMLoginProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回密碼建立日期，以及 IAM 使用者 `David` 是否需要重設密碼。**  

```
Get-IAMLoginProfile -UserName David
```
**輸出：**  

```
CreateDate                   PasswordResetRequired                 UserName
----------                   ---------------------                 --------
12/10/2014 3:39:44 PM        False                                 David
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMMFADevice`
<a name="iam_ListMfaDevices_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMMFADevice`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回指派給 IAM 使用者 `David` 之 MFA 裝置的詳細資訊。在此範例中，您可以確定這是虛擬裝置，因為 `SerialNumber` 是 ARN，而不是實體裝置的實際序號。**  

```
Get-IAMMFADevice -UserName David
```
**輸出：**  

```
EnableDate                  SerialNumber                           UserName
----------                  ------------                           --------
4/8/2015 9:41:10 AM         arn:aws:iam::123456789012:mfa/David    David
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMOpenIDConnectProvider`
<a name="iam_GetOpenIdConnectProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMOpenIDConnectProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 ARN 為 `arn:aws:iam::123456789012:oidc-provider/accounts.google.com` 的 OpenID Connect 提供者的詳細資訊。`ClientIDList` 屬性是一個集合，包含為此提供者定義的所有用戶端 ID。**  

```
Get-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/oidc.example.com
```
**輸出：**  

```
ClientIDList         CreateDate                ThumbprintList                               Url
------------         ----------                --------------                               ---
{MyOIDCApp}          2/3/2015 3:00:30 PM       {12345abcdefghijk67890lmnopqrst98765uvwxy}   oidc.example.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMOpenIDConnectProviderList`
<a name="iam_ListOpenIdConnectProviders_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMOpenIDConnectProviderList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回目前的 AWS 帳戶中定義之所有 OpenID Connect 提供者的 ARNS 清單。**  

```
Get-IAMOpenIDConnectProviderList
```
**輸出：**  

```
Arn
---
arn:aws:iam::123456789012:oidc-provider/server.example.com
arn:aws:iam::123456789012:oidc-provider/another.provider.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListOpenIdConnectProviders](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMPolicy`
<a name="iam_GetPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 ARN 為 `arn:aws:iam::123456789012:policy/MySamplePolicy` 之受管政策的詳細資訊。**  

```
Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**輸出：**  

```
Arn              : arn:aws:iam::aws:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 2/6/2015 10:40:08 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMPolicyList`
<a name="iam_ListPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMPolicyList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回目前 AWS 帳戶中可用的前三個受管政策的集合。由於 `-scope` 未指定，因此預設為 `all`，並同時包含 AWS 受管和客戶受管政策。**  

```
Get-IAMPolicyList -MaxItem 3
```
**輸出：**  

```
Arn              : arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : AWSDirectConnectReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:08 AM
      
Arn              : arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:27 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : NJKMU274MET4EEXAMPLE2
PolicyName       : AmazonGlacierReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:27 AM
      
Arn              : arn:aws:iam::aws:policy/AWSMarketplaceFullAccess
AttachmentCount  : 0
CreateDate       : 2/11/2015 9:21:45 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : 5ULJSO2FYVPYGEXAMPLE3
PolicyName       : AWSMarketplaceFullAccess
UpdateDate       : 2/11/2015 9:21:45 AM
```
**範例 2：此範例會傳回目前 AWS 帳戶中可用的前兩個客戶受管政策的集合。它使用 `-Scope local` 將輸出限制為僅限客戶管理政策。**  

```
Get-IAMPolicyList -Scope local -MaxItem 2
```
**輸出：**  

```
Arn              : arn:aws:iam::123456789012:policy/MyLocalPolicy
AttachmentCount  : 0
CreateDate       : 2/12/2015 9:39:09 AM
DefaultVersionId : v2
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : SQVCBLC4VAOUCEXAMPLE4
PolicyName       : MyLocalPolicy
UpdateDate       : 2/12/2015 9:39:53 AM

Arn              : arn:aws:iam::123456789012:policy/policyforec2instancerole
AttachmentCount  : 1
CreateDate       : 2/17/2015 2:51:38 PM
DefaultVersionId : v11
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : X5JPBLJH2Z2SOEXAMPLE5
PolicyName       : policyforec2instancerole
UpdateDate       : 2/18/2015 8:52:31 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMPolicyVersion`
<a name="iam_GetPolicyVersion_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMPolicyVersion`。

**Tools for PowerShell V5**  
**此範例會傳回 ARN 為 `arn:aws:iam::123456789012:policy/MyManagedPolicy` 之 `v2` 版本政策的政策文件。`Document` 屬性中的政策文件經過 URL 編碼，在此範例中使用 `UrlDecode` .NET 方法解碼。**  

```
$results = Get-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy -VersionId v2
$results
```
**輸出：**  

```
CreateDate             Document                                        IsDefaultVersion     VersionId
----------             --------                                        ----------------     ---------
2/12/2015 9:39:53 AM   %7B%0A%20%20%22Version%22%3A%20%222012-10...    True                 v2

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
$policy = [System.Web.HttpUtility]::UrlDecode($results.Document)
$policy
{
  "Version":"2012-10-17",		 	 	 
  "Statement": 
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMPolicyVersionList`
<a name="iam_ListPolicyVersions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMPolicyVersionList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 ARN 為 `arn:aws:iam::123456789012:policy/MyManagedPolicy` 之政策的可用版本清單。若要取得特定版本的政策文件，請使用 `Get-IAMPolicyVersion` 命令並指定想要文件的 `VersionId`。**  

```
Get-IAMPolicyVersionList -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy
```
**輸出：**  

```
CreateDate                   Document                 IsDefaultVersion                  VersionId
----------                   --------                 ----------------                  ---------
2/12/2015 9:39:53 AM                                  True                              v2
2/12/2015 9:39:09 AM                                  False                             v1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListPolicyVersions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMRole`
<a name="iam_GetRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMRole`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 `lamda_exec_role` 的詳細資訊。其中包含指定誰可以擔任此角色的信任政策文件。政策文件經過 URL 編碼，可以使用 .NET `UrlDecode` 方法解碼。在此範例中，原始政策在上傳至政策之前已移除所有空格。若要查看決定擔任該角色之人員可以執行的動作的許可政策文件，請將 `Get-IAMRolePolicy` 用於內嵌政策，並將 `Get-IAMPolicyVersion` 用於連接的受管政策。**  

```
$results = Get-IamRole -RoleName lambda_exec_role
$results | Format-List
```
**輸出：**  

```
Arn                      : arn:aws:iam::123456789012:role/lambda_exec_role
AssumeRolePolicyDocument : %7B%22Version%22%3A%222012-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22
                           %3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service
                           %22%3A%22lambda.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole
                           %22%7D%5D%7D
CreateDate               : 4/2/2015 9:16:11 AM
Path                     : /
RoleId                   : 2YBIKAIBHNKB4EXAMPLE1
RoleName                 : lambda_exec_role
```

```
$policy = [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
$policy
```
**輸出：**  

```
{"Version":"2012-10-17",		 	 	 "Statement":[{"Sid":"","Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMRoleList`
<a name="iam_ListRoles_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMRoleList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取 AWS 帳戶中所有 IAM 角色的清單。**  

```
Get-IAMRoleList
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListRoles](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMRolePolicy`
<a name="iam_GetRolePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMRolePolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回內嵌在 IAM 角色 `lamda_exec_role` 中的名為 `oneClick_lambda_exec_role_policy` 之政策的許可政策文件。產生的政策文件經過 URL 編碼。在此範例中，它會使用 `UrlDecode` .NET 方法解碼。**  

```
$results = Get-IAMRolePolicy -RoleName lambda_exec_role -PolicyName oneClick_lambda_exec_role_policy
$results
```
**輸出：**  

```
PolicyDocument                                            PolicyName                           UserName
--------------                                            ----------                           --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    oneClick_lambda_exec_role_policy     lambda_exec_role
```

```
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
```
**輸出：**  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:*"
      ],
      "Resource": "arn:aws:logs:us-east-1:555555555555:log-group:/aws/lambda/aws-example-function:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/*"
      ]
    }
  ]
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMRolePolicyList`
<a name="iam_ListRolePolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMRolePolicyList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回內嵌在 IAM 角色 `lamda_exec_role` 中之內嵌政策的名稱清單。若要查看內嵌政策的詳細資訊，請使用 `Get-IAMRolePolicy` 命令。**  

```
Get-IAMRolePolicyList -RoleName lambda_exec_role
```
**輸出：**  

```
oneClick_lambda_exec_role_policy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListRolePolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMRoleTagList`
<a name="iam_ListRoleTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMRoleTagList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取與角色關聯的標籤。**  

```
Get-IAMRoleTagList -RoleName MyRoleName
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListRoleTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMSAMLProvider`
<a name="iam_GetSamlProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMSAMLProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取 ARM 為 arn:aws:iam::123456789012:saml-provider/SAMLADFS 的 SAML 2.0 提供者的詳細資訊。回應包含您從身分提供者取得以建立 AWS SAML 提供者實體的中繼資料文件，以及建立和過期日期。**  

```
Get-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
**輸出：**  

```
CreateDate                 SAMLMetadataDocument                                          ValidUntil
----------                 --------------------                                          ----------
12/23/2014 12:16:55 PM    <EntityDescriptor ID="_12345678-1234-5678-9012-example1...    12/23/2114 12:16:54 PM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMSAMLProviderList`
<a name="iam_ListSAMLProviders_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMSAMLProviderList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取在目前 AWS 帳戶中建立的 SAML 2.0 提供者的清單。它會傳回每個 SAML 提供者的 ARN、建立日期和過期日期。**  

```
Get-IAMSAMLProviderList
```
**輸出：**  

```
Arn                                                 CreateDate                      ValidUntil
---                                                 ----------                      ----------
arn:aws:iam::123456789012:saml-provider/SAMLADFS    12/23/2014 12:16:55 PM          12/23/2114 12:16:54 PM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListSAMLProviders](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMServerCertificate`
<a name="iam_GetServerCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMServerCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取名為 `MyServerCertificate` 之伺服器憑證的詳細資訊。可以在 `CertificateBody` 和 `ServerCertificateMetadata` 屬性中找到憑證詳細資訊。**  

```
$result = Get-IAMServerCertificate -ServerCertificateName MyServerCertificate
$result | format-list
```
**輸出：**  

```
CertificateBody           : -----BEGIN CERTIFICATE-----
                            MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                            VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                            b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                            BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                            MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                            VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                            b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                            YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                            21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                            rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                            Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                            nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                            FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                            NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                            -----END CERTIFICATE-----
CertificateChain          : 
ServerCertificateMetadata : Amazon.IdentityManagement.Model.ServerCertificateMetadata
```

```
$result.ServerCertificateMetadata
```
**輸出：**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMServerCertificateList`
<a name="iam_ListServerCertificates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMServerCertificateList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取已上傳至目前 AWS 帳戶的伺服器憑證的清單。**  

```
Get-IAMServerCertificateList
```
**輸出：**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListServerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMServiceLastAccessedDetail`
<a name="iam_GetServiceLastAccessedDetails_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMServiceLastAccessedDetail`。

**Tools for PowerShell V5**  
**範例 1：此範例提供請求呼叫中關聯之 IAM 實體 (使用者、群組、角色或政策) 上次存取的服務詳細資訊。**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
**輸出：**  

```
f0b7a819-eab0-929b-dc26-ca598911cb9f
```

```
Get-IAMServiceLastAccessedDetail -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMServiceLastAccessedDetailWithEntity`
<a name="iam_GetServiceLastAccessedDetailsWithEntities_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMServiceLastAccessedDetailWithEntity`。

**Tools for PowerShell V5**  
**範例 1：此範例提供在請求中，該個別 IAM 實體上次存取服務的時間戳記。**  

```
$results = Get-IAMServiceLastAccessedDetailWithEntity -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f -ServiceNamespace ec2
$results
```
**輸出：**  

```
EntityDetailsList : {Amazon.IdentityManagement.Model.EntityDetails}
Error             : 
IsTruncated       : False
JobCompletionDate : 12/29/19 11:19:31 AM
JobCreationDate   : 12/29/19 11:19:31 AM
JobStatus         : COMPLETED
Marker            :
```

```
$results.EntityDetailsList
```
**輸出：**  

```
EntityInfo                                 LastAuthenticated
----------                                 -----------------
Amazon.IdentityManagement.Model.EntityInfo 11/16/19 3:47:00 PM
```

```
$results.EntityInfo
```
**輸出：**  

```
Arn  : arn:aws:iam::123456789012:user/TestUser
Id   : AIDA4NBK5CXF5TZHU1234
Name : TestUser
Path : /
Type : USER
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetServiceLastAccessedDetailsWithEntities](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMSigningCertificate`
<a name="iam_ListSigningCertificates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMSigningCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例擷取與名為 `Bob` 之使用者關聯的簽署憑證的詳細資訊。**  

```
Get-IAMSigningCertificate -UserName Bob
```
**輸出：**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListSigningCertificates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMUser`
<a name="iam_GetUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取名為 `David` 之使用者的詳細資訊。**  

```
Get-IAMUser -UserName David
```
**輸出：**  

```
Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE1
UserName         : David
```
**範例 2：此範例會擷取目前登入之 IAM 使用者的詳細資訊。**  

```
Get-IAMUser
```
**輸出：**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 10/16/2014 9:03:09 AM
PasswordLastUsed : 3/4/2015 12:12:33 PM
Path             : /
UserId           : 7K3GJEANSKZF2EXAMPLE2
UserName         : Bob
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMUserList`
<a name="iam_ListUsers_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMUserList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取目前 中的使用者集合 AWS 帳戶。**  

```
Get-IAMUserList
```
**輸出：**  

```
      Arn              : arn:aws:iam::123456789012:user/Administrator
      CreateDate       : 10/16/2014 9:03:09 AM
      PasswordLastUsed : 3/4/2015 12:12:33 PM
      Path             : /
      UserId           : 7K3GJEANSKZF2EXAMPLE1
      UserName         : Administrator
      
      Arn              : arn:aws:iam::123456789012:user/Bob
      CreateDate       : 4/6/2015 12:54:42 PM
      PasswordLastUsed : 1/1/0001 12:00:00 AM
      Path             : /
      UserId           : L3EWNONDOM3YUEXAMPLE2
      UserName         : bab
      
      Arn              : arn:aws:iam::123456789012:user/David
      CreateDate       : 12/10/2014 3:39:27 PM
      PasswordLastUsed : 3/19/2015 8:44:04 AM
      Path             : /
      UserId           : Y4FKWQCXTA52QEXAMPLE3
      UserName         : David
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListUsers](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMUserPolicy`
<a name="iam_GetUserPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMUserPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取內嵌在名為 `David` 之 IAM 使用者中的內嵌政策 `Davids_IAM_Admin_Policy` 的詳細資訊。政策文件經過 URL 編碼。**  

```
$results = Get-IAMUserPolicy -PolicyName Davids_IAM_Admin_Policy -UserName David
$results
```
**輸出：**  

```
PolicyDocument                                            PolicyName                    UserName
--------------                                            ----------                    --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    Davids_IAM_Admin_Policy       David

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:GetUser",
        "iam:ListUsers"
      ],
      "Resource": [
        "arn:aws:iam::111122223333:user/*"
      ]
    }
  ]
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMUserPolicyList`
<a name="iam_ListUserPolicies_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMUserPolicyList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取內嵌在名為 `David` 之 IAM 使用者中的內嵌政策的名稱清單。**  

```
Get-IAMUserPolicyList -UserName David
```
**輸出：**  

```
Davids_IAM_Admin_Policy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListUserPolicies](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMUserTagList`
<a name="iam_ListUserTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMUserTagList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取與使用者關聯的標籤。**  

```
Get-IAMUserTagList -UserName joe
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListUserTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMVirtualMFADevice`
<a name="iam_ListVirtualMfaDevices_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-IAMVirtualMFADevice`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取指派給 AWS 帳戶中使用者的虛擬 MFA 裝置集合。每個裝置的 `User` 屬性是一個物件，包含裝置被分派給的 IAM 使用者的詳細資訊。**  

```
Get-IAMVirtualMFADevice -AssignmentStatus Assigned
```
**輸出：**  

```
Base32StringSeed : 
EnableDate       : 4/13/2015 12:03:42 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/David
User             : Amazon.IdentityManagement.Model.User

Base32StringSeed : 
EnableDate       : 4/13/2015 12:06:41 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/root-account-mfa-device
User             : Amazon.IdentityManagement.Model.User
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListVirtualMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMAccessKey`
<a name="iam_CreateAccessKey_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMAccessKey`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的存取金鑰和私密存取金鑰對，並將其指派給使用者 `David`。請確定將 `AccessKeyId` 和 `SecretAccessKey` 值儲存到檔案中，因為這是唯一可以取得 `SecretAccessKey` 的時機。您稍後便無法擷取它。若您遺失了密碼金鑰，必須建立新的存取金鑰對。**  

```
New-IAMAccessKey -UserName David
```
**輸出：**  

```
AccessKeyId     : AKIAIOSFODNN7EXAMPLE
CreateDate      : 4/13/2015 1:00:42 PM
SecretAccessKey : wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Status          : Active
UserName        : David
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMAccountAlias`
<a name="iam_CreateAccountAlias_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMAccountAlias`。

**Tools for PowerShell V5**  
**範例 1：此範例會將您帳戶 AWS 的帳戶別名變更為 `mycompanyaws`。使用者登入頁面的網址會變更為 https://mycompanyaws.signin.aws.amazon.com/console。使用您的帳戶 ID 號碼而非別名的原始 URL (https://<accountidnumber>.signin.aws.amazon.com/console) 繼續有效。但是，任何先前定義的別名型 URL 已失效。**  

```
New-IAMAccountAlias -AccountAlias mycompanyaws
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAccountAlias](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMGroup`
<a name="iam_CreateGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `Developers` 的新 IAM 群組。**  

```
New-IAMGroup -GroupName Developers
```
**輸出：**  

```
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 4/14/2015 11:21:31 AM
GroupId    : QNEJ5PM4NFSQCEXAMPLE1
GroupName  : Developers
Path       : /
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMInstanceProfile`
<a name="iam_CreateInstanceProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMInstanceProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `ProfileForDevEC2Instance` 的新 IAM 執行個體設定檔。必須單獨執行 `Add-IAMRoleToInstanceProfile` 命令，將執行個體設定檔與為執行個體提供許可的現有 IAM 角色關聯起來。最後，在啟動執行個體時，將執行個體設定檔連接到 EC2 執行個體。為此，請使用含 `InstanceProfile_Arn` 或 `InstanceProfile_Name` 參數的 `New-EC2Instance` cmdlet。**  

```
New-IAMInstanceProfile -InstanceProfileName ProfileForDevEC2Instance
```
**輸出：**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ProfileForDevEC2Instance
CreateDate          : 4/14/2015 11:31:39 AM
InstanceProfileId   : DYMFXL556EY46EXAMPLE1
InstanceProfileName : ProfileForDevEC2Instance
Path                : /
Roles               : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMLoginProfile`
<a name="iam_CreateLoginProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMLoginProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會為名為 Bob 的 IAM 使用者建立 (臨時) 密碼並設定在 `Bob` 下次登入時要求使用者變更密碼的旗標。**  

```
New-IAMLoginProfile -UserName Bob -Password P@ssw0rd -PasswordResetRequired $true
```
**輸出：**  

```
CreateDate                    PasswordResetRequired                UserName
----------                    ---------------------                --------
4/14/2015 12:26:30 PM         True                                 Bob
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMOpenIDConnectProvider`
<a name="iam_CreateOpenIdConnectProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMOpenIDConnectProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立與 URL `https://example.oidcprovider.com` 和用戶端 ID `my-testapp-1` 中的 OIDC 相容提供者服務關聯的 IAM OIDC 提供者。OIDC 提供者會提供指紋。若要驗證指紋，請依照 http://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc-obtain-thumbprint.html 中的步驟進行。**  

```
New-IAMOpenIDConnectProvider -Url https://example.oidcprovider.com -ClientIDList my-testapp-1 -ThumbprintList 990F419EXAMPLEECF12DDEDA5EXAMPLE52F20D9E
```
**輸出：**  

```
arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMPolicy`
<a name="iam_CreatePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會在名為 檔案的目前 AWS 帳戶中建立新的 IAM `MySamplePolicy` 政策`MySamplePolicy.json`提供政策內容。請注意，必須使用 `-Raw` 切換參數，才能成功處理 JSON 政策檔案。**  

```
New-IAMPolicy -PolicyName MySamplePolicy -PolicyDocument (Get-Content -Raw MySamplePolicy.json)
```
**輸出：**  

```
Arn              : arn:aws:iam::123456789012:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 4/14/2015 2:45:59 PM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : LD4KP6HVFE7WGEXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 4/14/2015 2:45:59 PM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreatePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMPolicyVersion`
<a name="iam_CreatePolicyVersion_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMPolicyVersion`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新 v2 版的 IAM 政策 (其 ARN 為 `arn:aws:iam::123456789012:policy/MyPolicy`)，並將該版本設為預設版本。`NewPolicyVersion.json` 檔案會提供政策內容。請注意，必須使用 `-Raw` 切換參數，才能成功處理 JSON 政策檔案。**  

```
New-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -PolicyDocument (Get-content -Raw NewPolicyVersion.json) -SetAsDefault $true
```
**輸出：**  

```
CreateDate                           Document                  IsDefaultVersion             VersionId
----------                           --------                  ----------------             ---------
4/15/2015 10:54:54 AM                                          True                         v2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreatePolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMRole`
<a name="iam_CreateRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMRole`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `MyNewRole` 的新角色，並將其連接至在 `NewRoleTrustPolicy.json` 檔案中找到的政策。請注意，必須使用 `-Raw` 切換參數，才能成功處理 JSON 政策檔案。輸出中顯示的政策文件是以 URL 編碼。在此範例中，它會使用 `UrlDecode` .NET 方法解碼。**  

```
$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole
$results
```
**輸出：**  

```
Arn                      : arn:aws:iam::123456789012:role/MyNewRole
AssumeRolePolicyDocument : %7B%0D%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0D%0A%20%20%22Statement%22
                           %3A%20%5B%0D%0A%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%22Sid%22%3A%20%22%22%2C
                           %0D%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0D%0A%20%20%20%20%20%20
                           %22Principal%22%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%22AWS%22%3A%20%22arn%3Aaws
                           %3Aiam%3A%3A123456789012%3ADavid%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20
                           %20%20%20%22Action%22%3A%20%22sts%3AAssumeRole%22%0D%0A%20%20%20%20%7D%0D%0A%20
                           %20%5D%0D%0A%7D
CreateDate               : 4/15/2015 11:04:23 AM
Path                     : /
RoleId                   : V5PAJI2KPN4EAEXAMPLE1
RoleName                 : MyNewRole

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:David"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMSAMLProvider`
<a name="iam_CreateSAMLProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMSAMLProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 IAM 中建立新的 SAML 提供者實體。它被命名為 `MySAMLProvider`，由在檔案 `SAMLMetaData.xml` 中找到的 SAML 中繼資料文件描述，該檔案需從 SAML 服務提供者的網站單獨下載。**  

```
New-IAMSAMLProvider -Name MySAMLProvider -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
**輸出：**  

```
arn:aws:iam::123456789012:saml-provider/MySAMLProvider
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateSAMLProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMServiceLinkedRole`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立用於自動擴展服務的服務連結角色。**  

```
New-IAMServiceLinkedRole -AWSServiceName autoscaling.amazonaws.com -CustomSuffix RoleNameEndsWithThis -Description "My service-linked role to support autoscaling"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateServiceLinkedRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMUser`
<a name="iam_CreateUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `Bob` 的 IAM 使用者。如果 Bob 需要登入 AWS 主控台，則您必須分別執行 命令`New-IAMLoginProfile`，以使用密碼建立登入設定檔。如果 Bob 需要執行 AWS PowerShell 或跨平台 CLI 命令或進行 AWS API 呼叫，則必須單獨執行`New-IAMAccessKey`命令來建立存取金鑰。**  

```
New-IAMUser -UserName Bob
```
**輸出：**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 4/22/2015 12:02:11 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : AIDAJWGEFDMEMEXAMPLE1
UserName         : Bob
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMVirtualMFADevice`
<a name="iam_CreateVirtualMfaDevice_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-IAMVirtualMFADevice`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的虛擬 MFA 裝置。第 2 行和第 3 行擷取虛擬 MFA 軟體程式建立帳戶所需的 `Base32StringSeed` 值 (做為 QR 程式碼的替代方案)。使用值設定程式後，依序從程式取得兩個驗證碼。最後，使用最後一個命令將虛擬 MFA 裝置連結至 IAM 使用者 `Bob`，並使用兩個驗證碼同步帳戶。**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$SR = New-Object System.IO.StreamReader($Device.Base32StringSeed)
$base32stringseed = $SR.ReadToEnd()
$base32stringseed   
CZWZMCQNW4DEXAMPLE3VOUGXJFZYSUW7EXAMPLECR4NJFD65GX2SLUDW2EXAMPLE
```
**輸出：**  

```
-- Pause here to enter base-32 string seed code into virtual MFA program to register account. --

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
**範例 2：此範例會建立新的虛擬 MFA 裝置。第 2 行和第 3 行會擷取 `QRCodePNG` 值，並將其寫入檔案。此映像可由虛擬 MFA 軟體程式掃描，以建立帳戶 (做為手動輸入 Base32StringSeed 值的替代方案)。在虛擬 MFA 程式中建立帳戶後，請依序取得兩個驗證碼，並在最後一個命令中輸入它們，將虛擬 MFA 裝置連結至 IAM 使用者 `Bob` 並同步帳戶。**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$BR = New-Object System.IO.BinaryReader($Device.QRCodePNG)
$BR.ReadBytes($BR.BaseStream.Length) | Set-Content -Encoding Byte -Path QRCode.png
```
**輸出：**  

```
 -- Pause here to scan PNG with virtual MFA program to register account. -- 

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Publish-IAMServerCertificate`
<a name="iam_UploadServerCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Publish-IAMServerCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會將新伺服器憑證上傳至 IAM 帳戶。包含憑證內文、私有金鑰和 (可選) 憑證鏈的檔案全都必須採用 PEM 編碼。請注意，參數需要檔案的實際內容，而不是檔案名稱。必須使用 `-Raw` 切換參數，才能成功處理檔案內容。**  

```
Publish-IAMServerCertificate -ServerCertificateName MyTestCert -CertificateBody (Get-Content -Raw server.crt) -PrivateKey (Get-Content -Raw server.key)
```
**輸出：**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/MyTestCert
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /
ServerCertificateId   : ASCAJIEXAMPLE7J7HQZYW
ServerCertificateName : MyTestCert
UploadDate            : 4/21/2015 11:14:16 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UploadServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Publish-IAMSigningCertificate`
<a name="iam_UploadSigningCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Publish-IAMSigningCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會上傳新的 X.509 簽署憑證，並將其與名為 `Bob` 的 IAM 使用者關聯起來。包含憑證內文的檔案經過 PEM 編碼。`CertificateBody` 參數需要憑證檔案的實際內容，而不是檔案名稱。必須使用 `-Raw` 切換參數才能成功處理檔案。**  

```
Publish-IAMSigningCertificate -UserName Bob -CertificateBody (Get-Content -Raw SampleSigningCert.pem)
```
**輸出：**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCEXAMPLEHMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UploadSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-IAMGroupPolicy`
<a name="iam_AttachGroupPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-IAMGroupPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會將名為 `TesterPolicy` 的客戶管理政策連接到 IAM 群組 `Testers`。該群組中的使用者會立即受到該政策預設版本中定義之許可影響。**  

```
Register-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**範例 2：此範例會將名為 的 AWS 受管政策連接至 `AdministratorAccess` IAM 群組 `Admins`。該群組中的使用者會立即受到該政策最新版本中定義之許可影響。**  

```
Register-IAMGroupPolicy -GroupName Admins -PolicyArn arn:aws:iam::aws:policy/AdministratorAccess
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-IAMRolePolicy`
<a name="iam_AttachRolePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-IAMRolePolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會將名為 的 AWS 受管政策連接至 `SecurityAudit` IAM 角色 `CoSecurityAuditors`。該最新版本政策中所定義的許可會立即影響擔任該角色的使用者。**  

```
Register-IAMRolePolicy -RoleName CoSecurityAuditors -PolicyArn arn:aws:iam::aws:policy/SecurityAudit
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-IAMUserPolicy`
<a name="iam_AttachUserPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-IAMUserPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會將名為 `AmazonCognitoPowerUser`的 AWS 受管政策連接至 IAM 使用者 `Bob`。該最新版本政策中所定義的許可會立即影響使用者。**  

```
Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AttachUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMAccessKey`
<a name="iam_DeleteAccessKey_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMAccessKey`。

**Tools for PowerShell V5**  
**範例 1：此範例`AKIAIOSFODNN7EXAMPLE`會從名為 的使用者中刪除具有金鑰 ID 的 AWS 存取金鑰對`Bob`。**  

```
Remove-IAMAccessKey -AccessKeyId AKIAIOSFODNN7EXAMPLE -UserName Bob -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMAccountAlias`
<a name="iam_DeleteAccountAlias_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMAccountAlias`。

**Tools for PowerShell V5**  
**範例 1：此範例會從 中移除帳戶別名 AWS 帳戶。在 https://mycompanyaws.signin.aws.amazon.com/console，使用者無法再使用別名登入頁面。您必須改為在 https：//https://<accountidnumber>.signin.aws.amazon.com/console 使用原始 URL 搭配您的 AWS 帳戶 ID 號碼。**  

```
Remove-IAMAccountAlias -AccountAlias mycompanyaws
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteAccountAlias](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMAccountPasswordPolicy`
<a name="iam_DeleteAccountPasswordPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMAccountPasswordPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 的密碼政策， AWS 帳戶 並將所有值重設為其原始預設值。如果密碼政策目前不存在，則會出現下列錯誤訊息：找不到名為 PasswordPolicy 的帳戶政策。**  

```
Remove-IAMAccountPasswordPolicy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMClientIDFromOpenIDConnectProvider`
<a name="iam_RemoveClientIdFromOpenIdConnectProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMClientIDFromOpenIDConnectProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會從與 ARN 為 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` 的 IAM OIDC 提供者關聯的用戶端 ID 清單中移除用戶端 ID `My-TestApp-3`。**  

```
Remove-IAMClientIDFromOpenIDConnectProvider -ClientID My-TestApp-3 -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveClientIdFromOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMGroup`
<a name="iam_DeleteGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除名為 `MyTestGroup` 的 IAM 群組。第一個命令會移除所有屬於群組的 IAM 使用者，第二個命令則會刪除 IAM 群組。這兩個命令皆可在沒有任何確認提示的情況下運作。**  

```
(Get-IAMGroup -GroupName MyTestGroup).Users | Remove-IAMUserFromGroup -GroupName MyTestGroup -Force
Remove-IAMGroup -GroupName MyTestGroup -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMGroupPolicy`
<a name="iam_DeleteGroupPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMGroupPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會從 IAM 群組 `Testers` 中移除名為 `TesterPolicy` 的內嵌政策。該群組中的使用者會立即失去此政策中定義的許可。**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMInstanceProfile`
<a name="iam_DeleteInstanceProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMInstanceProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除名為 `MyAppInstanceProfile` 的 EC2 執行個體設定檔。第一個命令將從執行個體設定檔分離任何角色，然後第二個命令將刪除執行個體設定檔。**  

```
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMLoginProfile`
<a name="iam_DeleteLoginProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMLoginProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會從名為 `Bob` 的 IAM 使用者中刪除登入設定檔。這可防止使用者登入 AWS 主控台。它不會阻止使用者使用可能仍連接至使用者帳戶的 AWS 存取金鑰來執行任何 AWS CLI、PowerShell 或 API 呼叫。**  

```
Remove-IAMLoginProfile -UserName Bob
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMOpenIDConnectProvider`
<a name="iam_DeleteOpenIdConnectProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMOpenIDConnectProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除連線至提供者 `example.oidcprovider.com` 的 IAM OIDC 提供者。請確定更新或刪除在角色信任政策的 `Principal` 元素中引用此提供者的任何角色。**  

```
Remove-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMPolicy`
<a name="iam_DeletePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 ARN 為 `arn:aws:iam::123456789012:policy/MySamplePolicy` 的政策。在刪除政策之前，必須先執行 `Remove-IAMPolicyVersion` 刪除除預設版本之外的所有版本。還必須將政策與任何 IAM 使用者、群組或角色分離。**  

```
Remove-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**範例 2：此範例會刪除政策，方法是先刪除所有非預設政策版本，將其與所有連接的 IAM 實體分離，最後刪除政策本身。第一行擷取政策物件。第二行擷取未標記為集合預設版本的所有政策版本，然後刪除集合中的每個政策。第三行擷取連接政策的所有 IAM 使用者、群組和角色。第四行到第六行將政策與每個連接的實體分離。最後一行使用此命令移除受管政策以及剩餘的預設版本。此範例會在任何需要 `-Force` 切換參數的行中加入該參數，以抑制確認提示。**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
$attached = Get-IAMEntitiesForPolicy -PolicyArn $pol.Arn
$attached.PolicyGroups | Unregister-IAMGroupPolicy -PolicyArn $pol.arn
$attached.PolicyRoles | Unregister-IAMRolePolicy -PolicyArn $pol.arn
$attached.PolicyUsers | Unregister-IAMUserPolicy -PolicyArn $pol.arn
Remove-IAMPolicy $pol.Arn -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMPolicyVersion`
<a name="iam_DeletePolicyVersion_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMPolicyVersion`。

**Tools for PowerShell V5**  
**範例 1：此範例會從 ARN 為 `arn:aws:iam::123456789012:policy/MySamplePolicy` 的政策中刪除標識為 `v2` 的版本。**  

```
Remove-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy -VersionID v2
```
**範例 2：此範例會先刪除所有非預設政策版本，然後刪除政策本身，從而刪除政策。第一行擷取政策物件。第二行擷取未標記為集合預設值的所有政策版本，然後使用此命令刪除集合中的每個政策。最後一行移除政策本身以及剩餘的預設版本。請注意，若要成功刪除受管政策，還必須使用 `Unregister-IAMUserPolicy`、`Unregister-IAMGroupPolicy` 和 `Unregister-IAMRolePolicy` 命令，將政策與任何使用者、群組或角色分離。請參閱 `Remove-IAMPolicy` cmdlet 的範例。**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
Remove-IAMPolicy -PolicyArn $pol.Arn -force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeletePolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMRole`
<a name="iam_DeleteRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMRole`。

**Tools for PowerShell V5**  
**範例 1：此範例會從目前的 IAM 帳戶刪除名為 `MyNewRole` 的角色。在刪除角色之前，必須先使用 `Unregister-IAMRolePolicy` 命令來分離任何受管政策。內嵌政策會與角色一起刪除。**  

```
Remove-IAMRole -RoleName MyNewRole
```
**範例 2：此範例會從名為 `MyNewRole` 的角色分離任何受管政策，然後刪除該角色。第一行將連接至角色的任何受管政策擷取為集合，然後讓集合中的每個政策與角色分離。第二行刪除角色本身。內嵌政策會與角色一起刪除。**  

```
Get-IAMAttachedRolePolicyList -RoleName MyNewRole | Unregister-IAMRolePolicy -RoleName MyNewRole
Remove-IAMRole -RoleName MyNewRole
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMRoleFromInstanceProfile`
<a name="iam_RemoveRoleFromInstanceProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMRoleFromInstanceProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會將名為 `MyNewRole` 的角色從名為 `MyNewRole` 的 EC2 執行個體設定檔中刪除。在 IAM 主控台中建立的執行個體設定檔一律與角色同名，如本範例中所示。如果您在 API 或 CLI 中建立它們，則它們可以有不同的名稱。**  

```
Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyNewRole -RoleName MyNewRole -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMRolePermissionsBoundary`
<a name="iam_DeleteRolePermissionsBoundary_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMRolePermissionsBoundary`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何移除連接至 IAM 角色的許可界限。**  

```
Remove-IAMRolePermissionsBoundary -RoleName MyRoleName
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMRolePolicy`
<a name="iam_DeleteRolePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMRolePolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除內嵌在 IAM 角色 `S3BackupRole` 中的內嵌政策 `S3AccessPolicy`。**  

```
Remove-IAMRolePolicy -PolicyName S3AccessPolicy -RoleName S3BackupRole
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMRoleTag`
<a name="iam_UntagRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMRoleTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會從名為「MyRoleName」且標籤索引鍵為「abac」的角色中移除標籤。若要移除多個標籤，請提供以逗號分隔的標籤索引鍵清單。**  

```
Remove-IAMRoleTag -RoleName MyRoleName -TagKey "abac","xyzw"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UntagRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMSAMLProvider`
<a name="iam_DeleteSAMLProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMSAMLProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 ARN 為 `arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider` 的 IAM SAML 2.0 提供者。**  

```
Remove-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteSAMLProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMServerCertificate`
<a name="iam_DeleteServerCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMServerCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除名為 `MyServerCert` 的伺服器憑證。**  

```
Remove-IAMServerCertificate -ServerCertificateName MyServerCert
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMServiceLinkedRole`。

**Tools for PowerShell V5**  
**範例 1：此範例已經刪除服務連結的角色。請注意，如果服務仍在使用該角色，則此命令會導致失敗。**  

```
Remove-IAMServiceLinkedRole -RoleName AWSServiceRoleForAutoScaling_RoleNameEndsWithThis
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteServiceLinkedRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMSigningCertificate`
<a name="iam_DeleteSigningCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMSigningCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會從名為 `Bob` 的 IAM 使用者中刪除 ID 為 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` 的簽署憑證。**  

```
Remove-IAMSigningCertificate -UserName Bob -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMUser`
<a name="iam_DeleteUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除名為 `Bob` 的 IAM 使用者。**  

```
Remove-IAMUser -UserName Bob
```
**範例 2：此範例會刪除名為 `Theresa` 的 IAM 使用者以及任何必須先刪除的元素。**  

```
$name = "Theresa"

# find any groups and remove user from them
$groups = Get-IAMGroupForUser -UserName $name
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName $name -Force }

# find any inline policies and delete them
$inlinepols = Get-IAMUserPolicies -UserName $name
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName $name -Force}

# find any managed polices and detach them
$managedpols = Get-IAMAttachedUserPolicies -UserName $name
foreach ($pol in $managedpols) { Unregister-IAMUserPolicy -PolicyArn $pol.PolicyArn -UserName $name }

# find any signing certificates and delete them
$certs = Get-IAMSigningCertificate -UserName $name
foreach ($cert in $certs) { Remove-IAMSigningCertificate -CertificateId $cert.CertificateId -UserName $name -Force }

# find any access keys and delete them
$keys = Get-IAMAccessKey -UserName $name
foreach ($key in $keys) { Remove-IAMAccessKey -AccessKeyId $key.AccessKeyId -UserName $name -Force }

# delete the user's login profile, if one exists - note: need to use try/catch to suppress not found error
try { $prof = Get-IAMLoginProfile -UserName $name -ea 0 } catch { out-null }
if ($prof) { Remove-IAMLoginProfile -UserName $name -Force }

# find any MFA device, detach it, and if virtual, delete it.
$mfa = Get-IAMMFADevice -UserName $name
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}

# finally, remove the user
Remove-IAMUser -UserName $name -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMUserFromGroup`
<a name="iam_RemoveUserFromGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMUserFromGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會從 `Testers` 群組中移除 IAM 使用者 `Bob`。**  

```
Remove-IAMUserFromGroup -GroupName Testers -UserName Bob
```
**範例 2：此範例會尋找 IAM 使用者 `Theresa` 所屬的任意群組，然後從這些群組中移除 `Theresa`。**  

```
$groups = Get-IAMGroupForUser -UserName Theresa 
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName Theresa -Force }
```
**範例 3：此範例顯示從 `Testers` 群組中移除 IAM 使用者 `Bob` 的替代方式。**  

```
Get-IAMGroupForUser -UserName Bob | Remove-IAMUserFromGroup -UserName Bob -GroupName Testers -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveUserFromGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMUserPermissionsBoundary`
<a name="iam_DeleteUserPermissionsBoundary_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMUserPermissionsBoundary`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何移除連接到 IAM 使用者的許可界限。**  

```
Remove-IAMUserPermissionsBoundary -UserName joe
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMUserPolicy`
<a name="iam_DeleteUserPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMUserPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除內嵌在名為 `Bob` 之 IAM 使用者中的、名為 `AccessToEC2Policy` 的內嵌政策。**  

```
Remove-IAMUserPolicy -PolicyName AccessToEC2Policy -UserName Bob
```
**範例 2：此範例會尋找內嵌在名為 `Theresa` 的 IAM 使用者中的所有內嵌政策，然後將其刪除。**  

```
$inlinepols = Get-IAMUserPolicies -UserName Theresa
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName Theresa -Force}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMUserTag`
<a name="iam_UntagUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMUserTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會從名為「joe」且標籤索引鍵為「abac」和「xyzw」的使用者中移除標籤。若要移除多個標籤，請提供以逗號分隔的標籤索引鍵清單。**  

```
Remove-IAMUserTag -UserName joe -TagKey "abac","xyzw"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UntagUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMVirtualMFADevice`
<a name="iam_DeleteVirtualMfaDevice_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-IAMVirtualMFADevice`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 ARN 為 `arn:aws:iam::123456789012:mfa/bob` 的 IAM 虛擬 MFA 裝置。**  

```
Remove-IAMVirtualMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/bob
```
**範例 2：此範例會檢查 IAM 使用者 Theresa 是否已獲分派 MFA 裝置。如果找到一個，系統會為 IAM 使用者停用裝置。如果裝置是虛擬裝置，亦將刪除。**  

```
$mfa = Get-IAMMFADevice -UserName Theresa
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Request-IAMCredentialReport`
<a name="iam_GenerateCredentialReport_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Request-IAMCredentialReport`。

**Tools for PowerShell V5**  
**範例 1：此範例會請求產生新的報告，這可以每四小時執行一次。如果最後一個報告仍然是最新的，「狀態」欄位會顯示：`COMPLETE`。`Get-IAMCredentialReport` 可用於檢視已完成的報告。**  

```
Request-IAMCredentialReport
```
**輸出：**  

```
Description                                                    State
-----------                                                    -----
No report exists. Starting a new report generation task        STARTED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GenerateCredentialReport](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Request-IAMServiceLastAccessedDetail`
<a name="iam_GenerateServiceLastAccessedDetails_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Request-IAMServiceLastAccessedDetail`。

**Tools for PowerShell V5**  
**範例 1：此範例等同於 GenerateServiceLastAccessedDetails API 的 cmdlet。這提供了任務 ID，可用於 Get-IAMServiceLastAccessedDetail 和 Get-IAMServiceLastAccessedDetailWithEntity**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GenerateServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-IAMDefaultPolicyVersion`
<a name="iam_SetDefaultPolicyVersion_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-IAMDefaultPolicyVersion`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 ARN 為 `arn:aws:iam::123456789012:policy/MyPolicy` 的政策的 `v2` 版本設定為預設的作用中版本。**  

```
Set-IAMDefaultPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -VersionId v2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetDefaultPolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-IAMRolePermissionsBoundary`
<a name="iam_PutRolePermissionsBoundary_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-IAMRolePermissionsBoundary`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何設定 IAM 角色的許可界限。您可以將 AWS 受管政策或自訂政策設定為許可界限。**  

```
Set-IAMRolePermissionsBoundary -RoleName MyRoleName -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-IAMUserPermissionsBoundary`
<a name="iam_PutUserPermissionsBoundary_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-IAMUserPermissionsBoundary`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何設定使用者的許可界限。您可以將 AWS 受管政策或自訂政策設定為許可界限。 **  

```
Set-IAMUserPermissionsBoundary -UserName joe -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Sync-IAMMFADevice`
<a name="iam_ResyncMfaDevice_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Sync-IAMMFADevice`。

**Tools for PowerShell V5**  
**範例 1：此範例會將與 IAM 使用者 `Bob` 關聯且 ARN 為 `arn:aws:iam::123456789012:mfa/bob` 的 MFA 裝置，與提供兩個驗證碼的身分驗證器程式同步。**  

```
Sync-IAMMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/theresa -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Bob
```
**範例 2：此範例會將與 IAM 使用者 `Theresa` 關聯的 IAM MFA 裝置，與序號為 `ABCD12345678` 並提供兩個驗證碼的實體裝置同步。**  

```
Sync-IAMMFADevice -SerialNumber ABCD12345678 -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Theresa
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResyncMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-IAMGroupPolicy`
<a name="iam_DetachGroupPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-IAMGroupPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 ARN 為 `arn:aws:iam::123456789012:policy/TesterAccessPolicy` 的受管群組政策與名為 `Testers` 的群組分離。**  

```
Unregister-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterAccessPolicy
```
**範例 2：此範例會找出連接到名為 `Testers` 的群組的所有受管政策，並將其與群組分離。**  

```
Get-IAMAttachedGroupPolicies -GroupName Testers | Unregister-IAMGroupPolicy -Groupname Testers
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-IAMRolePolicy`
<a name="iam_DetachRolePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-IAMRolePolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 ARN 為 `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy` 的受管群組政策與名為 `FedTesterRole` 的角色分離。**  

```
Unregister-IAMRolePolicy -RoleName FedTesterRole -PolicyArn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy
```
**範例 2：此範例會找出連接到名為 `FedTesterRole` 的角色的所有受管政策，並將其與角色分離。**  

```
Get-IAMAttachedRolePolicyList -RoleName FedTesterRole | Unregister-IAMRolePolicy -Rolename FedTesterRole
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-IAMUserPolicy`
<a name="iam_DetachUserPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-IAMUserPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 ARN 為 `arn:aws:iam::123456789012:policy/TesterPolicy` 的受管政策與名為 `Bob` 的 IAM 使用者分離。**  

```
Unregister-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**範例 2：此範例會找出連接到名為 `Theresa` 的 IAM 使用者的所有受管政策，並將這些政策與使用者分離。**  

```
Get-IAMAttachedUserPolicyList -UserName Theresa | Unregister-IAMUserPolicy -Username Theresa
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DetachUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMAccessKey`
<a name="iam_UpdateAccessKey_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMAccessKey`。

**Tools for PowerShell V5**  
**範例 1：此範例會將名為 `Bob` 之 IAM 使用者的存取金鑰 `AKIAIOSFODNN7EXAMPLE` 的狀態變更為`Inactive`。**  

```
Update-IAMAccessKey -UserName Bob -AccessKeyId AKIAIOSFODNN7EXAMPLE -Status Inactive
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMAccountPasswordPolicy`
<a name="iam_UpdateAccountPasswordPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMAccountPasswordPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用指定設定更新帳戶的密碼政策。請注意，命令中未包含的任何參數都不會保持不變。相反，它們會重設為預設值。**  

```
Update-IAMAccountPasswordPolicy -AllowUsersToChangePasswords $true -HardExpiry $false -MaxPasswordAge 90 -MinimumPasswordLength 8 -PasswordReusePrevention 20 -RequireLowercaseCharacters $true -RequireNumbers $true -RequireSymbols $true -RequireUppercaseCharacters $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMAssumeRolePolicy`
<a name="iam_UpdateAssumeRolePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMAssumeRolePolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會使用新的信任政策更新名為 `ClientRole` 的 IAM 角色，其內容來自 `ClientRolePolicy.json` 檔案。請注意，必須使用 `-Raw` 切換參數，才能成功處理 JSON 檔案的內容。**  

```
Update-IAMAssumeRolePolicy -RoleName ClientRole -PolicyDocument (Get-Content -raw ClientRolePolicy.json)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateAssumeRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMGroup`
<a name="iam_UpdateGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 IAM 群組 `Testers` 重新命名為 `AppTesters`。**  

```
Update-IAMGroup -GroupName Testers -NewGroupName AppTesters
```
**範例 2：此範例會將 IAM 群組 `AppTesters` 的路徑變更為 `/Org1/Org2/`。這會將群組的 ARN 變更為 `arn:aws:iam::123456789012:group/Org1/Org2/AppTesters`。**  

```
Update-IAMGroup -GroupName AppTesters -NewPath /Org1/Org2/
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMLoginProfile`
<a name="iam_UpdateLoginProfile_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMLoginProfile`。

**Tools for PowerShell V5**  
**範例 1：此範例會為 IAM 使用者 `Bob` 設定新的臨時密碼，並在使用者下次登入時要求其變更密碼。**  

```
Update-IAMLoginProfile -UserName Bob -Password "P@ssw0rd1234" -PasswordResetRequired $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMOpenIDConnectProviderThumbprint`
<a name="iam_UpdateOpenIdConnectProviderThumbprint_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMOpenIDConnectProviderThumbprint`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新 ARN 為 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` 之 OIDC 提供者的憑證指紋清單，以使用新指紋。當與提供者關聯之憑證變更時，OIDC 提供者會共用新值。**  

```
Update-IAMOpenIDConnectProviderThumbprint -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com -ThumbprintList 7359755EXAMPLEabc3060bce3EXAMPLEec4542a3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateOpenIdConnectProviderThumbprint](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMRole`
<a name="iam_UpdateRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMRole`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新角色描述，以及可以請求角色工作階段的工作階段持續時間值上限 (以秒為單位)。**  

```
Update-IAMRole -RoleName MyRoleName -Description "My testing role" -MaxSessionDuration 43200
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMRoleDescription`
<a name="iam_UpdateRoleDescription_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMRoleDescription`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新您的帳戶中 IAM 角色的描述。**  

```
Update-IAMRoleDescription -RoleName MyRoleName -Description "My testing role"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateRoleDescription](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMSAMLProvider`
<a name="iam_UpdateSamlProvider_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMSAMLProvider`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新 IAM 中 ARN 為 `arn:aws:iam::123456789012:saml-provider/SAMLADFS`、使用檔案 `SAMLMetaData.xml` 中的新 SAML 中繼資料文件的 SAML 提供者。請注意，必須使用 `-Raw` 切換參數，才能成功處理 JSON 檔案的內容。**  

```
Update-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMServerCertificate`
<a name="iam_UpdateServerCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMServerCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會將名為 `MyServerCertificate` 的憑證重新命名為 `MyRenamedServerCertificate`。**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewServerCertificateName MyRenamedServerCertificate
```
**範例 2：此範例會將名為 `MyServerCertificate` 的憑證移至路徑 /Org1/Org2/。這會將資源的 ARN 變更為 `arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate`。**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewPath /Org1/Org2/
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMSigningCertificate`
<a name="iam_UpdateSigningCertificate_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMSigningCertificate`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新與名為 `Bob`、憑證 ID 為 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` 的 IAM 使用者關聯的憑證，將其標示為非作用中。**  

```
Update-IAMSigningCertificate -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU -UserName Bob -Status Inactive
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-IAMUser`
<a name="iam_UpdateUser_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-IAMUser`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 IAM 使用者 `Bob` 重新命名為 `Robert`。**  

```
Update-IAMUser -UserName Bob -NewUserName Robert
```
**範例 2：此範例會將 IAM 使用者 `Bob` 的路徑變更為 `/Org1/Org2/`，這可有效地將使用者的 ARN 變更為 `arn:aws:iam::123456789012:user/Org1/Org2/bob`。**  

```
Update-IAMUser -UserName Bob -NewPath /Org1/Org2/
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateUser](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-IAMGroupPolicy`
<a name="iam_PutGroupPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-IAMGroupPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `AppTesterPolicy` 的內嵌政策，並將其內嵌在 IAM 群組 `AppTesters` 中。如果已存在同名的內嵌政策，其會被覆寫。JSON 政策內容來自 `apptesterpolicy.json` 檔案。請注意，必須使用 `-Raw` 參數，才能成功處理 JSON 檔案的內容。**  

```
Write-IAMGroupPolicy -GroupName AppTesters -PolicyName AppTesterPolicy -PolicyDocument (Get-Content -Raw apptesterpolicy.json)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-IAMRolePolicy`
<a name="iam_PutRolePolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-IAMRolePolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `FedTesterRolePolicy` 的內嵌政策，並將其內嵌在 IAM 角色 `FedTesterRole` 中。如果已存在同名的內嵌政策，其會被覆寫。JSON 政策內容來自 `FedTesterPolicy.json` 檔案。請注意，必須使用 `-Raw` 參數，才能成功處理 JSON 檔案的內容。**  

```
Write-IAMRolePolicy -RoleName FedTesterRole -PolicyName FedTesterRolePolicy -PolicyDocument (Get-Content -Raw FedTesterPolicy.json)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-IAMUserPolicy`
<a name="iam_PutUserPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-IAMUserPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `EC2AccessPolicy` 的內嵌政策，並將其內嵌在 IAM 使用者 `Bob` 中。如果已存在同名的內嵌政策，其會被覆寫。JSON 政策內容來自 `EC2AccessPolicy.json` 檔案。請注意，必須使用 `-Raw` 參數，才能成功處理 JSON 檔案的內容。**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Kinesis 範例
<a name="powershell_kinesis_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Kinesis 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-KINRecord`
<a name="kinesis_GetRecords_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-KINRecord`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何從一系列的一或多個記錄，傳回和擷取資料。提供給 Get-KINRecord 的迭代器，能判斷記錄的開始位置，以傳回在此範例中擷取到變數 \$1records 的位置。然後，您可以透過編製 \$1records 集合的索引來存取每個個別記錄。假設記錄中的資料為 UTF-8 編碼文字，最終命令會示範如何從物件中的 MemoryStream 擷取資料，並將其當作文字傳回至主控台。**  

```
$records
$records = Get-KINRecord -ShardIterator "AAAAAAAAAAGIc....9VnbiRNaP"
```
**輸出：**  

```
MillisBehindLatest NextShardIterator            Records
------------------ -----------------            -------
0                  AAAAAAAAAAERNIq...uDn11HuUs  {Key1, Key2}
```

```
$records.Records[0]
```
**輸出：**  

```
ApproximateArrivalTimestamp Data                   PartitionKey SequenceNumber
--------------------------- ----                   ------------ --------------
3/7/2016 5:14:33 PM         System.IO.MemoryStream Key1         4955986459776...931586
```

```
[Text.Encoding]::UTF8.GetString($records.Records[0].Data.ToArray())
```
**輸出：**  

```
test data from string
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetRecords](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-KINShardIterator`
<a name="kinesis_GetShardIterator_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-KINShardIterator`。

**Tools for PowerShell V5**  
**範例 1：傳回指定碎片和開始位置的碎片迭代器。碎片識別碼和序號的詳細資訊，可從 Get-KINStream Cmdlet 的輸出取得，方法是參考傳回串流物件的碎片收集。傳回的迭代器可與 Get-KINRecord Cmdlet 搭配使用，以提取碎片中的資料記錄。**  

```
Get-KINShardIterator -StreamName "mystream" -ShardId "shardId-000000000000" -ShardIteratorType AT_SEQUENCE_NUMBER -StartingSequenceNumber "495598645..."
```
**輸出：**  

```
AAAAAAAAAAGIc....9VnbiRNaP
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetShardIterator](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-KINStream`
<a name="kinesis_DescribeStream_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-KINStream`。

**Tools for PowerShell V5**  
**範例 1：傳回指定串流的詳細資訊。**  

```
Get-KINStream -StreamName "mystream"
```
**輸出：**  

```
HasMoreShards        : False
RetentionPeriodHours : 24
Shards               : {}
StreamARN            : arn:aws:kinesis:us-west-2:123456789012:stream/mystream
StreamName           : mystream
StreamStatus         : ACTIVE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStream](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-KINStream`
<a name="kinesis_CreateStream_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-KINStream`。

**Tools for PowerShell V5**  
**範例 1：建立新的串流。**  

```
New-KINStream -StreamName "mystream" -ShardCount 1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateStream](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-KINStream`
<a name="kinesis_DeleteStream_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-KINStream`。

**Tools for PowerShell V5**  
**範例 1：刪除指定的串流。在執行命令之前，系統會提示您確認。若要隱藏確認提示，請使用 -Force 切換變數。**  

```
Remove-KINStream -StreamName "mystream"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteStream](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-KINRecord`
<a name="kinesis_PutRecord_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-KINRecord`。

**Tools for PowerShell V5**  
**範例 1：撰寫包含提供給 -Text 參數之字串的記錄。**  

```
Write-KINRecord -Text "test data from string" -StreamName "mystream" -PartitionKey "Key1"
```
**範例 2：寫入包含在指定檔案中的資料的記錄。該檔案會被視為位元組序列，因此如果其包含文字，則應在搭配此 Cmdlet 使用之前，使用任何必要的編碼進行編寫。**  

```
Write-KINRecord -FilePath "C:\TestData.txt" -StreamName "mystream" -PartitionKey "Key2"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutRecord](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Lambda 範例
<a name="powershell_lambda_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Lambda 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-LMResourceTag`
<a name="lambda_TagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-LMResourceTag`。

**Tools for PowerShell V5**  
**範例 1：將三個標籤 (華盛頓、奧勒岡和加利佛尼亞) 及其相關聯的值新增至其 ARN 識別的指定函數。**  

```
Add-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -Tag @{ "Washington" = "Olympia"; "Oregon" = "Salem"; "California" = "Sacramento" }
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMAccountSetting`
<a name="lambda_GetAccountSettings_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMAccountSetting`。

**Tools for PowerShell V5**  
**範例 1：此範例會顯示以比較帳戶限制和帳戶用量**  

```
Get-LMAccountSetting | Select-Object @{Name="TotalCodeSizeLimit";Expression={$_.AccountLimit.TotalCodeSize}}, @{Name="TotalCodeSizeUsed";Expression={$_.AccountUsage.TotalCodeSize}}
```
**輸出：**  

```
TotalCodeSizeLimit TotalCodeSizeUsed
------------------ -----------------
       80530636800          15078795
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAccountSettings](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMAlias`
<a name="lambda_GetAlias_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMAlias`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取特定 Lambda 函數別名的路由組態權重。**  

```
Get-LMAlias -FunctionName "MylambdaFunction123" -Name "newlabel1" -Select RoutingConfig
```
**輸出：**  

```
AdditionalVersionWeights
------------------------
{[1, 0.6]}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAlias](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMFunctionConcurrency`
<a name="lambda_GetFunctionConcurrency_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMFunctionConcurrency`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得 Lambda 函數的預留並行**  

```
Get-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -Select *
```
**輸出：**  

```
ReservedConcurrentExecutions
----------------------------
100
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMFunctionConfiguration`
<a name="lambda_GetFunctionConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMFunctionConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 Lambda 函數的版本特定組態。**  

```
Get-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Qualifier "PowershellAlias"
```
**輸出：**  

```
CodeSha256                 : uWOW0R7z+f0VyLuUg7+/D08hkMFsq0SF4seuyUZJ/R8=
CodeSize                   : 1426
DeadLetterConfig           : Amazon.Lambda.Model.DeadLetterConfig
Description                : Verson 3 to test Aliases
Environment                : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn                : arn:aws:lambda:us-east-1:123456789012:function:MylambdaFunction123
                             :PowershellAlias
FunctionName               : MylambdaFunction123
Handler                    : lambda_function.launch_instance
KMSKeyArn                  : 
LastModified               : 2019-12-25T09:52:59.872+0000
LastUpdateStatus           : Successful
LastUpdateStatusReason     : 
LastUpdateStatusReasonCode : 
Layers                     : {}
MasterArn                  : 
MemorySize                 : 128
RevisionId                 : 5d7de38b-87f2-4260-8f8a-e87280e10c33
Role                       : arn:aws:iam::123456789012:role/service-role/lambda
Runtime                    : python3.8
State                      : Active
StateReason                : 
StateReasonCode            : 
Timeout                    : 600
TracingConfig              : Amazon.Lambda.Model.TracingConfigResponse
Version                    : 4
VpcConfig                  : Amazon.Lambda.Model.VpcConfigDetail
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetFunctionConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMFunctionList`
<a name="lambda_ListFunctions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMFunctionList`。

**Tools for PowerShell V5**  
**範例 1：此範例會顯示具有已排序程式碼大小的所有 Lambda 函數**  

```
Get-LMFunctionList | Sort-Object -Property CodeSize | Select-Object FunctionName, RunTime, Timeout, CodeSize
```
**輸出：**  

```
FunctionName                                                 Runtime   Timeout CodeSize
------------                                                 -------   ------- --------
test                                                         python2.7       3      243
MylambdaFunction123                                          python3.8     600      659
myfuncpython1                                                python3.8     303      675
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListFunctions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMPolicy`
<a name="lambda_GetPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMPolicy`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示 Lambda 函數的函數政策**  

```
Get-LMPolicy -FunctionName test -Select Policy
```
**輸出：**  

```
{"Version":"2012-10-17",		 	 	 "Id":"default","Statement":[{"Sid":"xxxx","Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-1:123456789102:function:test"}]}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMProvisionedConcurrencyConfig`
<a name="lambda_GetProvisionedConcurrencyConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMProvisionedConcurrencyConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得 Lambda 函數指定別名的已佈建並行組態。**  

```
C:\>Get-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
**輸出：**  

```
AllocatedProvisionedConcurrentExecutions : 0
AvailableProvisionedConcurrentExecutions : 0
LastModified                             : 2020-01-15T03:21:26+0000
RequestedProvisionedConcurrentExecutions : 70
Status                                   : IN_PROGRESS
StatusReason                             :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMProvisionedConcurrencyConfigList`
<a name="lambda_ListProvisionedConcurrencyConfigs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMProvisionedConcurrencyConfigList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取 Lambda 函數的已佈建並行組態清單。**  

```
Get-LMProvisionedConcurrencyConfigList -FunctionName "MylambdaFunction123"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListProvisionedConcurrencyConfigs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMResourceTag`
<a name="lambda_ListTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMResourceTag`。

**Tools for PowerShell V5**  
**範例 1：擷取目前在指定函數中設定的標籤及其值。**  

```
Get-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
**輸出：**  

```
Key        Value
---        -----
California Sacramento
Oregon     Salem
Washington Olympia
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-LMVersionsByFunction`
<a name="lambda_ListVersionsByFunction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-LMVersionsByFunction`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回每個 Lambda 函數版本的版本特定組態清單。**  

```
Get-LMVersionsByFunction -FunctionName "MylambdaFunction123"
```
**輸出：**  

```
FunctionName        Runtime   MemorySize Timeout CodeSize LastModified                 RoleName
------------        -------   ---------- ------- -------- ------------                 --------
MylambdaFunction123 python3.8        128     600      659 2020-01-10T03:20:56.390+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:19:02.238+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:39:36.779+0000 lambda
MylambdaFunction123 python3.8        128     600     1426 2019-12-25T09:52:59.872+0000 lambda
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListVersionsByFunction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-LMAlias`
<a name="lambda_CreateAlias_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-LMAlias`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的版本和路由組態建立新的 Lambda 別名，以指定其收到的調用請求百分比。**  

```
New-LMAlias -FunctionName "MylambdaFunction123" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6} -Description "Alias for version 4" -FunctionVersion 4 -Name "PowershellAlias"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAlias](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Publish-LMFunction`
<a name="lambda_CreateFunction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Publish-LMFunction`。

**Tools for PowerShell V5**  
**範例 1：此範例會在 AWS Lambda 中建立新的 C\$1 (dotnetcore1.0 執行時間） 函數名為 MyFunction，提供從本機檔案系統上 zip 檔案的函數編譯二進位檔 （可使用相對或絕對路徑）。C\$1 Lambda 函數會使用 AssemblyName::Namespace.ClassName::MethodName 指派方法來指定函數的處理常式。您應該適當地取代處理常式規格的組件名稱 (不含 .dll 尾碼)、命名空間、類別名稱和方法名稱部分。新函數將透過提供的值來設定環境變數 'envvar1' 和 'envvar2'。**  

```
Publish-LMFunction -Description "My C# Lambda Function" `
        -FunctionName MyFunction `
        -ZipFilename .\MyFunctionBinaries.zip `
        -Handler "AssemblyName::Namespace.ClassName::MethodName" `
        -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" `
        -Runtime dotnetcore1.0 `
        -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
```
**輸出：**  

```
CodeSha256       : /NgBMd...gq71I=
CodeSize         : 214784
DeadLetterConfig :
Description      : My C# Lambda Function
Environment      : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn      : arn:aws:lambda:us-west-2:123456789012:function:ToUpper
FunctionName     : MyFunction
Handler          : AssemblyName::Namespace.ClassName::MethodName
KMSKeyArn        :
LastModified     : 2016-12-29T23:50:14.207+0000
MemorySize       : 128
Role             : arn:aws:iam::123456789012:role/LambdaFullExecRole
Runtime          : dotnetcore1.0
Timeout          : 3
Version          : $LATEST
VpcConfig        :
```
**範例 2：此範例類似於上一個範例，但函數二進位檔會先上傳到 Amazon S3 儲存貯體 (必須與預期的 Lambda 函數位於相同區域)，然後在建立函數時參考產生的 S3 物件。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key MyFunctionBinaries.zip -File .\MyFunctionBinaries.zip    
Publish-LMFunction -Description "My C# Lambda Function" `
        -FunctionName MyFunction `
        -BucketName amzn-s3-demo-bucket `
        -Key MyFunctionBinaries.zip `
        -Handler "AssemblyName::Namespace.ClassName::MethodName" `
        -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" `
        -Runtime dotnetcore1.0 `
        -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateFunction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Publish-LMVersion`
<a name="lambda_PublishVersion_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Publish-LMVersion`。

**Tools for PowerShell V5**  
**範例 1：此範例會為 Lambda 函數程式碼的現有快照建立版本**  

```
Publish-LMVersion -FunctionName "MylambdaFunction123" -Description "Publishing Existing Snapshot of function code as a  new version through Powershell"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PublishVersion](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-LMAlias`
<a name="lambda_DeleteAlias_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-LMAlias`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除命令中提到的 Lambda 函數別名。**  

```
Remove-LMAlias -FunctionName "MylambdaFunction123" -Name "NewAlias"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteAlias](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-LMFunction`
<a name="lambda_DeleteFunction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-LMFunction`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除 Lambda 函數的特定版本**  

```
Remove-LMFunction -FunctionName "MylambdaFunction123" -Qualifier '3'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteFunction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-LMFunctionConcurrency`
<a name="lambda_DeleteFunctionConcurrency_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-LMFunctionConcurrency`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除 Lambda 函數的函數並行。**  

```
Remove-LMFunctionConcurrency -FunctionName "MylambdaFunction123"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-LMPermission`
<a name="lambda_RemovePermission_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-LMPermission`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除 Lambda 函數之指定 StatementId 的函數政策。**  

```
$policy =  Get-LMPolicy -FunctionName "MylambdaFunction123" -Select Policy | ConvertFrom-Json| Select-Object -ExpandProperty Statement
Remove-LMPermission -FunctionName "MylambdaFunction123" -StatementId $policy[0].Sid
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemovePermission](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-LMProvisionedConcurrencyConfig`
<a name="lambda_DeleteProvisionedConcurrencyConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-LMProvisionedConcurrencyConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除特定別名的已佈建並行組態。**  

```
Remove-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-LMResourceTag`
<a name="lambda_UntagResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-LMResourceTag`。

**Tools for PowerShell V5**  
**範例 1：從函數中移除提供的標籤。除非已指定 -Force 切換，否則 cmdlet 會提示進行確認。對服務進行單一呼叫以移除標籤。**  

```
Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -TagKey "Washington","Oregon","California"
```
**範例 2：從函數中移除提供的標籤。除非已指定 -Force 切換，否則 cmdlet 會提示進行確認。按照提供的標籤對服務進行呼叫後。**  

```
"Washington","Oregon","California" | Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-LMAlias`
<a name="lambda_UpdateAlias_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-LMAlias`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新現有 Lambda 函數別名的組態。它會更新 RoutingConfiguration 值，將 60% (0.6) 的流量轉移到第 1 版**  

```
Update-LMAlias -FunctionName "MylambdaFunction123" -Description " Alias for version 2" -FunctionVersion 2 -Name "newlabel1" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateAlias](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-LMFunctionCode`
<a name="lambda_UpdateFunctionCode_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-LMFunctionCode`。

**Tools for PowerShell V5**  
**範例 1：使用指定 zip 檔案中包含的新內容，更新名為 'MyFunction' 的函數。對於 C\$1 .NET Core Lambda 函數，zip 檔案應包含已編譯的組件。**  

```
Update-LMFunctionCode -FunctionName MyFunction -ZipFilename .\UpdatedCode.zip
```
**範例 2：此範例類似於上一個範例，但使用包含更新程式碼的 Amazon S3 物件來更新函數。**  

```
Update-LMFunctionCode -FunctionName MyFunction -BucketName amzn-s3-demo-bucket -Key UpdatedCode.zip
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateFunctionCode](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-LMFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-LMFunctionConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新現有的 Lambda 函數組態**  

```
Update-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Handler "lambda_function.launch_instance" -Timeout 600 -Environment_Variable @{ "envvar1"="value";"envvar2"="value" } -Role arn:aws:iam::123456789101:role/service-role/lambda -DeadLetterConfig_TargetArn arn:aws:sns:us-east-1: 123456789101:MyfirstTopic
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateFunctionConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-LMFunctionConcurrency`
<a name="lambda_PutFunctionConcurrency_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-LMFunctionConcurrency`。

**Tools for PowerShell V5**  
**範例 1：此範例會整體套用函數的並行設定。**  

```
Write-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -ReservedConcurrentExecution 100
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-LMProvisionedConcurrencyConfig`
<a name="lambda_PutProvisionedConcurrencyConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-LMProvisionedConcurrencyConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會將佈建並行組態新增至函數別名**  

```
Write-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -ProvisionedConcurrentExecution 20 -Qualifier "NewAlias1"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon ML 範例
<a name="powershell_machine-learning_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon ML 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-MLBatchPrediction`
<a name="machine-learning_GetBatchPrediction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLBatchPrediction`。

**Tools for PowerShell V5**  
**範例 1：傳回具有該 ID 的批次預測的詳細中繼資料。**  

```
Get-MLBatchPrediction -BatchPredictionId ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBatchPrediction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLBatchPredictionList`
<a name="machine-learning_DescribeBatchPredictions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLBatchPredictionList`。

**Tools for PowerShell V5**  
**範例 1：傳回符合請求中給定搜尋條件的所有 BatchPredictions 及其相關聯資料記錄的清單。**  

```
Get-MLBatchPredictionList
```
**範例 2：傳回狀態為 COMPLETED 的所有 BatchPredictions 的清單。**  

```
Get-MLBatchPredictionList -FilterVariable Status -EQ COMPLETED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeBatchPredictions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLDataSource`
<a name="machine-learning_GetDataSource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLDataSource`。

**Tools for PowerShell V5**  
**範例 1：傳回 id 為 ID 之 DataSource 的中繼資料、狀態和資料檔案資訊**  

```
Get-MLDataSource -DataSourceId ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDataSource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLDataSourceList`
<a name="machine-learning_DescribeDataSources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLDataSourceList`。

**Tools for PowerShell V5**  
**範例 1：傳回所有 DataSources 及其相關聯資料記錄的清單。**  

```
Get-MLDataSourceList
```
**範例 2：傳回狀態為 COMPLETED 的所有 DataSources 清單。**  

```
Get-MLDataDourceList -FilterVariable Status -EQ COMPLETED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDataSources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLEvaluation`
<a name="machine-learning_GetEvaluation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLEvaluation`。

**Tools for PowerShell V5**  
**範例 1：傳回具有 ID 之評估的中繼資料和狀態。**  

```
Get-MLEvaluation -EvaluationId ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetEvaluation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLEvaluationList`
<a name="machine-learning_DescribeEvaluations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLEvaluationList`。

**Tools for PowerShell V5**  
**範例 1：傳回所有評估資源的清單**  

```
Get-MLEvaluationList
```
**範例 2：傳回狀態為 COMPLETED 的所有評估清單。**  

```
Get-MLEvaluationList -FilterVariable Status -EQ COMPLETED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEvaluations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLModel`
<a name="machine-learning_GetMLModel_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLModel`。

**Tools for PowerShell V5**  
**範例 1：傳回 id 為 ID 之 MLModel 的詳細資訊中繼資料、狀態、結構描述和資料檔案資訊。**  

```
Get-MLModel -ModelId ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetMLModel](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLModelList`
<a name="machine-learning_DescribeMLModels_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLModelList`。

**Tools for PowerShell V5**  
**範例 1：傳回所有模型及其相關聯資料記錄的清單。**  

```
Get-MLModelList
```
**範例 2：傳回狀態為 COMPLETED 的所有模型清單。**  

```
Get-MLModelList -FilterVariable Status -EQ COMPLETED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMLModels](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLPrediction`
<a name="machine-learning_Predict_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MLPrediction`。

**Tools for PowerShell V5**  
**範例 1：將記錄傳送至 id 為 ID 之模型的即時預測端點 URL。**  

```
Get-MLPrediction -ModelId ID -PredictEndpoint URL -Record @{"A" = "B"; "C" = "D";}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Predict](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLBatchPrediction`
<a name="machine-learning_CreateBatchPrediction_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-MLBatchPrediction`。

**Tools for PowerShell V5**  
**範例 1：為 id 為 ID 之模型建立新的批次預測請求，並將輸出放在指定的 S3 位置。**  

```
New-MLBatchPrediction -ModelId ID -Name NAME -OutputURI s3://...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateBatchPrediction](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLDataSourceFromS3`
<a name="machine-learning_CreateDataSourceFromS3_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-MLDataSourceFromS3`。

**Tools for PowerShell V5**  
**範例 1：使用 S3 位置的資料建立資料來源，其名稱為 NAME，結構描述為 SCHEMA。**  

```
New-MLDataSourceFromS3 -Name NAME -ComputeStatistics $true -DataSpec_DataLocationS3 "s3://BUCKET/KEY" -DataSchema SCHEMA
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDataSourceFromS3](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLEvaluation`
<a name="machine-learning_CreateEvaluation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-MLEvaluation`。

**Tools for PowerShell V5**  
**範例 1：為給定的資料來源 ID 和模型 ID 建立評估**  

```
New-MLEvaluation -Name NAME -DataSourceId DSID -ModelId MID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateEvaluation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLModel`
<a name="machine-learning_CreateMLModel_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-MLModel`。

**Tools for PowerShell V5**  
**範例 1：使用訓練資料建立新模型。**  

```
New-MLModel -Name NAME -ModelType BINARY -Parameter @{...} -TrainingDataSourceId ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateMLModel](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLRealtimeEndpoint`
<a name="machine-learning_CreateRealtimeEndpoint_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-MLRealtimeEndpoint`。

**Tools for PowerShell V5**  
**範例 1：為給定的模型 ID 建立新的即時預測端點。**  

```
New-MLRealtimeEndpoint -ModelId ID
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateRealtimeEndpoint](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Macie 範例
<a name="powershell_macie2_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Macie 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-MAC2FindingList`
<a name="macie2_ListFindings_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-MAC2FindingList`。

**Tools for PowerShell V5**  
**範例 1：傳回包含類型為 "CREDIT\$1CARD\$1NUMBER" 或 "US\$1SOCIAL\$1SECURITY\$1NUMBER" 之敏感資料偵測的調查結果的 FindingIds 清單**  

```
$criterionAddProperties = New-Object Amazon.Macie2.Model.CriterionAdditionalProperties

$criterionAddProperties.Eq = @(
"CREDIT_CARD_NUMBER"
"US_SOCIAL_SECURITY_NUMBER"
)

$FindingCriterion = @{
'classificationDetails.result.sensitiveData.detections.type' = [Amazon.Macie2.Model.CriterionAdditionalProperties]$criterionAddProperties
}

Get-MAC2FindingList -FindingCriteria_Criterion $FindingCriterion -MaxResult 5
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListFindings](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS 價格表 使用 Tools for PowerShell V5 的範例
<a name="powershell_pricing_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS 價格表。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-PLSAttributeValue`
<a name="pricing_GetAttributeValues_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-PLSAttributeValue`。

**Tools for PowerShell V5**  
**範例 1：傳回 us-east-1 區域中 Amazon EC2 之屬性 'volumeType' 的值。**  

```
Get-PLSAttributeValue -ServiceCode AmazonEC2 -AttributeName "volumeType" -region us-east-1
```
**輸出：**  

```
Value
-----
Cold HDD
General Purpose
Magnetic
Provisioned IOPS
Throughput Optimized HDD
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAttributeValues](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-PLSProduct`
<a name="pricing_GetProducts_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-PLSProduct`。

**Tools for PowerShell V5**  
**範例 1：傳回 Amazon EC2 的所有產品的詳細資訊。**  

```
Get-PLSProduct -ServiceCode AmazonEC2 -Region us-east-1
```
**輸出：**  

```
{"product":{"productFamily":"Compute Instance","attributes":{"enhancedNetworkingSupported":"Yes","memory":"30.5 GiB","dedicatedEbsThroughput":"800 Mbps","vcpu":"4","locationType":"AWS Region","storage":"EBS only","instanceFamily":"Memory optimized","operatingSystem":"SUSE","physicalProcessor":"Intel Xeon E5-2686 v4 (Broadwell)","clockSpeed":"2.3 GHz","ecu":"Variable","networkPerformance":"Up to 10 Gigabit","servicename":"Amazon Elastic Compute Cloud","instanceType":"r4.xlarge","tenancy":"Shared","usagetype":"USW2-BoxUsage:r4.xlarge","normalizationSizeFactor":"8","processorFeatures":"Intel AVX, Intel AVX2, Intel Turbo","servicecode":"AmazonEC2","licenseModel":"No License required","currentGeneration":"Yes","preInstalledSw":"NA","location":"US West (Oregon)","processorArchitecture":"64-bit","operation":"RunInstances:000g"},...
```
**範例 2：傳回 us-east-1 區域中的 Amazon EC2 資料，這些資料依照 SSD 支援的「一般用途」磁碟區類型進行篩選。**  

```
Get-PLSProduct -ServiceCode AmazonEC2 -Filter @{Type="TERM_MATCH";Field="volumeType";Value="General Purpose"},@{Type="TERM_MATCH";Field="storageMedia";Value="SSD-backed"} -Region us-east-1
```
**輸出：**  

```
{"product":{"productFamily":"Storage","attributes":{"storageMedia":"SSD-backed","maxThroughputvolume":"160 MB/sec","volumeType":"General Purpose","maxIopsvolume":"10000",...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetProducts](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-PLSService`
<a name="pricing_DescribeServices_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-PLSService`。

**Tools for PowerShell V5**  
**範例 1：傳回 us-east-1 區域中所有可用服務代碼的中繼資料。**  

```
Get-PLSService -Region us-east-1
```
**輸出：**  

```
AttributeNames                                                  ServiceCode
--------------                                                  -----------
{productFamily, servicecode, groupDescription, termType...}     AWSBudgets
{productFamily, servicecode, termType, usagetype...}            AWSCloudTrail
{productFamily, servicecode, termType, usagetype...}            AWSCodeCommit
{productFamily, servicecode, termType, usagetype...}            AWSCodeDeploy
{productFamily, servicecode, termType, usagetype...}            AWSCodePipeline
{productFamily, servicecode, termType, usagetype...}            AWSConfig
...
```
**範例 2：傳回 us-east-1 區域中 Amazon EC2 服務的中繼資料。**  

```
Get-PLSService -ServiceCode AmazonEC2 -Region us-east-1
```
**輸出：**  

```
AttributeNames                                                         ServiceCode
--------------                                                         -----------
{volumeType, maxIopsvolume, instanceCapacity10xlarge, locationType...} AmazonEC2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Resource Groups 範例
<a name="powershell_resource-groups_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配資源群組來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-RGResourceTag`
<a name="resource-groups_Tag_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-RGResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將值為 'workboxes' 的標籤索引鍵 'Instances'，新增至給定的資源群組 arn**  

```
Add-RGResourceTag -Tag @{Instances="workboxes"} -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes
```
**輸出：**  

```
Arn                                                            Tags
---                                                            ----
arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes {[Instances, workboxes]}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Tag](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Find-RGResource`
<a name="resource-groups_SearchResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Find-RGResource`。

**Tools for PowerShell V5**  
**範例 1：此範例使用標籤篩選條件，為執行個體資源類型建立 ResourceQuery，並尋找資源。**  

```
$query = [Amazon.ResourceGroups.Model.ResourceQuery]::new()
$query.Type = [Amazon.ResourceGroups.QueryType]::TAG_FILTERS_1_0
$query.Query = ConvertTo-Json -Compress -Depth 4 -InputObject @{
  ResourceTypeFilters = @('AWS::EC2::Instance')
  TagFilters = @(@{
    Key = 'auto'
    Values = @('no')
  })
 }

Find-RGResource -ResourceQuery $query | Select-Object -ExpandProperty ResourceIdentifiers
```
**輸出：**  

```
ResourceArn                                                     ResourceType
-----------                                                     ------------
arn:aws:ec2:eu-west-1:123456789012:instance/i-0123445b6cb7bd67b AWS::EC2::Instance
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SearchResources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGGroup`
<a name="resource-groups_GetGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會根據群組名稱擷取資源群組**  

```
Get-RGGroup -GroupName auto-no
```
**輸出：**  

```
Description GroupArn                                                     Name
----------- --------                                                     ----
            arn:aws:resource-groups:eu-west-1:123456789012:group/auto-no auto-no
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGGroupList`
<a name="resource-groups_ListGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGGroupList`。

**Tools for PowerShell V5**  
**範例 1：此範例會列出已建立的資源群組。**  

```
Get-RGGroupList
```
**輸出：**  

```
GroupArn                                                                  GroupName
--------                                                                  ---------
arn:aws:resource-groups:eu-west-1:123456789012:group/auto-no              auto-no
arn:aws:resource-groups:eu-west-1:123456789012:group/auto-yes             auto-yes
arn:aws:resource-groups:eu-west-1:123456789012:group/build600             build600
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGGroupQuery`
<a name="resource-groups_GetGroupQuery_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGGroupQuery`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取給定資源群組的資源查詢**  

```
Get-RGGroupQuery -GroupName auto-no | Select-Object -ExpandProperty ResourceQuery
```
**輸出：**  

```
Query                                                                                        Type
-----                                                                                        ----
{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"auto","Values":["no"]}]} TAG_FILTERS_1_0
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetGroupQuery](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGGroupResourceList`
<a name="resource-groups_ListGroupResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGGroupResourceList`。

**Tools for PowerShell V5**  
**範例 1：此範例根據依資源類型的篩選，列出群組資源**  

```
Get-RGGroupResourceList -Filter @{Name="resource-type";Values="AWS::EC2::Instance"} -GroupName auto-yes | Select-Object -ExpandProperty ResourceIdentifiers
```
**輸出：**  

```
ResourceArn                                                     ResourceType
-----------                                                     ------------
arn:aws:ec2:eu-west-1:123456789012:instance/i-0123bc45b567890e1 AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-0a1caf2345f67d8dc AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-0fd12dd3456789012 AWS::EC2::Instance
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListGroupResources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGResourceTag`
<a name="resource-groups_GetTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會列出給定資源群組 arn 的標籤**  

```
Get-RGResourceTag -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes
```
**輸出：**  

```
Key       Value
---       -----
Instances workboxes
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-RGGroup`
<a name="resource-groups_CreateGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-RGGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立新的標籤型 AWS 資源群組資源群組，名為 TestPowerShellGroup。群組包含目前區域中，以標籤索引鍵 "Name" 和標籤值 "test2" 標記的 Amazon EC2 執行個體。命令會傳回群組的查詢和類型，以及操作的結果。**  

```
$ResourceQuery = New-Object -TypeName Amazon.ResourceGroups.Model.ResourceQuery
$ResourceQuery.Type = "TAG_FILTERS_1_0"
$ResourceQuery.Query = '{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"Name","Values":["test2"]}]}'
$ResourceQuery

New-RGGroup -Name TestPowerShellGroup -ResourceQuery $ResourceQuery -Description "Test resource group."
```
**輸出：**  

```
Query                                                                                           Type           
-----                                                                                           ----           
{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"Name","Values":["test2"]}]} TAG_FILTERS_1_0

LoggedAt         : 11/20/2018 2:40:59 PM
Group            : Amazon.ResourceGroups.Model.Group
ResourceQuery    : Amazon.ResourceGroups.Model.ResourceQuery
Tags             : {}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 338
HttpStatusCode   : OK
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-RGGroup`
<a name="resource-groups_DeleteGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-RGGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除具名資源群組**  

```
Remove-RGGroup -GroupName non-tag-cfn-elbv2
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-RGGroup (DeleteGroup)" on target "non-tag-cfn-elbv2".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Description GroupArn                                                               Name
----------- --------                                                               ----
            arn:aws:resource-groups:eu-west-1:123456789012:group/non-tag-cfn-elbv2 non-tag-cfn-elbv2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-RGResourceTag`
<a name="resource-groups_Untag_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-RGResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會從資源群組中移除提及的標籤**  

```
Remove-RGResourceTag -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes -Key Instances
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-RGResourceTag (Untag)" on target "arn:aws:resource-groups:eu-west-1:933303704102:group/workboxes".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Arn                                                            Keys
---                                                            ----
arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes {Instances}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Untag](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-RGGroup`
<a name="resource-groups_UpdateGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-RGGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會更新群組的描述**  

```
Update-RGGroup -GroupName auto-yes -Description "Instances auto-remove"
```
**輸出：**  

```
Description             GroupArn                                                      Name
-----------             --------                                                      ----
Instances to be cleaned arn:aws:resource-groups:eu-west-1:123456789012:group/auto-yes auto-yes
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-RGGroupQuery`
<a name="resource-groups_UpdateGroupQuery_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-RGGroupQuery`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立查詢物件，並更新群組的查詢。**  

```
$query = [Amazon.ResourceGroups.Model.ResourceQuery]::new()
$query.Type = [Amazon.ResourceGroups.QueryType]::TAG_FILTERS_1_0
$query.Query = @{
  ResourceTypeFilters = @('AWS::EC2::Instance')
  TagFilters = @(@{
  Key='Environment'
  Values='Build600.11'
  })
} | ConvertTo-Json -Compress -Depth 4

Update-RGGroupQuery -GroupName build600 -ResourceQuery $query
```
**輸出：**  

```
GroupName ResourceQuery
--------- -------------
build600  Amazon.ResourceGroups.Model.ResourceQuery
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateGroupQuery](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的資源群組標記 API 範例
<a name="powershell_resource-groups-tagging-api_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配資源群組標記 API 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-RGTResourceTag`
<a name="resource-groups-tagging-api_TagResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-RGTResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將值為 "beta" 和 "preprod\$1test" 的標籤索引鍵 "stage" 和 "version"，新增至 Amazon S3 儲存貯體和 Amazon DynamoDB 資料表。對服務進行單一呼叫以套用標籤。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

Add-RGTResourceTag -ResourceARNList $arn1,$arn2 -Tag @{ "stage"="beta"; "version"="preprod_test" }
```
**範例 2：此範例會將指定的標籤和值，新增至 Amazon S3 儲存貯體和 Amazon DynamoDB 資料表。對服務進行兩次呼叫，每個資源 ARN 傳輸一個呼叫到 Cmdlet。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

$arn1,$arn2 | Add-RGTResourceTag -Tag @{ "stage"="beta"; "version"="preprod_test" }
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TagResources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGTResource`
<a name="resource-groups-tagging-api_GetResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGTResource`。

**Tools for PowerShell V5**  
**範例 1：傳回區域中所有標記的資源，以及與資源相關聯的標籤索引鍵。如果未將 -Region 參數提供給 Cmdlet，則會嘗試從 Shell 或 EC2 執行個體中繼資料推斷區域。**  

```
Get-RGTResource
```
**輸出：**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}   
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**範例 2：傳回區域中指定之類型的所有已標記資源。每個服務名稱和資源類型的字串，與嵌入資源的 Amazon Resource Name (ARN) 的字串相同。**  

```
Get-RGTResource -ResourceType "s3"
```
**輸出：**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**範例 3：傳回區域中指定之類型的所有已標記資源。請注意，當資源類型傳輸到 Cmdlet 時，針對每個提供的資源類型呼叫一次服務。**  

```
"dynamodb","s3" | Get-RGTResource
```
**輸出：**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}   
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**範例 4：傳回符合指定之篩選條件的所有已標記資源。**  

```
Get-RGTResource -TagFilter @{ Key="stage" }
```
**輸出：**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**範例 5：傳回符合指定之篩選條件和資源類型的所有已標記資源。**  

```
Get-RGTResource -TagFilter @{ Key="stage" } -ResourceType "dynamodb"
```
**輸出：**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}
```
**範例 6：傳回符合指定之篩選條件的所有已標記資源。**  

```
Get-RGTResource -TagFilter @{ Key="stage"; Values=@("beta","gamma") }
```
**輸出：**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetResources](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGTTagKey`
<a name="resource-groups-tagging-api_GetTagKeys_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGTTagKey`。

**Tools for PowerShell V5**  
**範例 1：傳回指定區域中的所有標籤索引鍵。如果未指定 -Region 參數，Cmdlet 會嘗試從預設 Shell 區域或 EC2 執行個體中繼資料推斷區域。請注意，標籤索引鍵不會以任何特定順序傳回。**  

```
Get-RGTTagKey -region us-west-2
```
**輸出：**  

```
version
stage
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetTagKeys](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-RGTTagValue`
<a name="resource-groups-tagging-api_GetTagValues_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-RGTTagValue`。

**Tools for PowerShell V5**  
**範例 1：傳回區域中指定標籤的值。如果未指定 -Region 參數，Cmdlet 會嘗試從預設 Shell 區域或 EC2 執行個體中繼資料推斷區域。**  

```
Get-RGTTagValue -Key "stage" -Region us-west-2
```
**輸出：**  

```
beta
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetTagValues](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-RGTResourceTag`
<a name="resource-groups-tagging-api_UntagResources_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-RGTResourceTag`。

**Tools for PowerShell V5**  
**範例 1：從 Amazon S3 儲存貯體和 Amazon DynamoDB 資料表中移除標籤索引鍵 "stage" 和 "version"，以及相關聯的值。對服務進行單一呼叫以移除標籤。在移除標籤之前，Cmdlet 會提示確認。要略過確認，請新增 -Force 切換變數。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

Remove-RGTResourceTag -ResourceARNList $arn1,$arn2 -TagKey "stage","version"
```
**範例 2：從 Amazon S3 儲存貯體和 Amazon DynamoDB 資料表中移除標籤索引鍵 "stage" 和 "version"，以及相關聯的值。對服務進行兩次呼叫，每個資源 ARN 傳輸一個呼叫到 Cmdlet。每一次呼叫之前，Cmdlet 都會提示確認。要略過確認，請新增 -Force 切換變數。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

$arn1,$arn2 | Remove-RGTResourceTag -TagKey "stage","version"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UntagResources](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Route 53 範例
<a name="powershell_route-53_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Route 53 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Edit-R53ResourceRecordSet`
<a name="route-53_ChangeResourceRecordSets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-R53ResourceRecordSet`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立 www.example.com 的 A 記錄，並將 test.example.com 的 A 記錄從 192.0.2.3 變更為 192.0.2.1。請注意，變更 TXT 類型記錄的值，必須以雙引號括住。如需詳細資訊，請參閱 Amazon Route 53 文件。您可以使用 Get-R53Change Cmdlet 輪詢，判斷變更何時完成。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "TXT"
$change1.ResourceRecordSet.TTL = 600
$change1.ResourceRecordSet.ResourceRecords = @()
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="item 1 item 2 item 3"})

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "DELETE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "test.example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.TTL = 600
$change2.ResourceRecordSet.ResourceRecords = @()
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.3"})

$change3 = New-Object Amazon.Route53.Model.Change
$change3.Action = "CREATE"
$change3.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change3.ResourceRecordSet.Name = "test.example.com"
$change3.ResourceRecordSet.Type = "A"
$change3.ResourceRecordSet.TTL = 600
$change3.ResourceRecordSet.ResourceRecords = @()
$change3.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.1"})

$params = @{
    HostedZoneId="Z1PA6795UKMFR9"
	ChangeBatch_Comment="This change batch creates a TXT record for www.example.com. and changes the A record for test.example.com. from 192.0.2.3 to 192.0.2.1."
	ChangeBatch_Change=$change1,$change2,$change3
}

Edit-R53ResourceRecordSet @params
```
**範例 2：此範例示範如何建立別名資源記錄集。'Z222222222' 是您要建立別名資源記錄集的 Amazon Route 53 託管區域 ID。'example.com' 是您要建立別名的 Zone Apex，而 'www.example.com' 是您也想要建立別名的子網域。'Z1111111111111' 是負載平衡器託管區域 ID 的範例，而 'example-load-balancer-1111111111.us-east-1.elb.amazonaws.com' 則是負載平衡器網域名稱的範例，Amazon Route 53 便是使用該網域名稱回應對 example.com 和 www.example.com 的查詢。如需詳細資訊，請參閱 Amazon Route 53 文件。您可以使用 Get-R53Change Cmdlet 輪詢，判斷變更何時完成。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $false

$params = @{
    HostedZoneId="Z222222222"
	ChangeBatch_Comment="This change batch creates two alias resource record sets, one for the zone apex, example.com, and one for www.example.com, that both point to example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
	ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**範例 3：此範例會為 www.example.com 建立兩個 A 記錄。四分之一的時間 (1/(1\$13))，Amazon Route 53 會使用第一個資源記錄集 (192.0.2.9 和 192.0.2.10) 的兩個值，回應 www.example.com 的查詢。四分之三的時間 (3/(1\$13)) Amazon Route 53 會使用第二個資源記錄集 (192.0.2.11 和 192.0.2.12) 的兩個值，回應 www.example.com 的查詢。如需詳細資訊，請參閱 Amazon Route 53 文件。您可以使用 Get-R53Change Cmdlet 輪詢，判斷變更何時完成。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "Rack 2, Positions 4 and 5"
$change1.ResourceRecordSet.Weight = 1
$change1.ResourceRecordSet.TTL = 600
$change1.ResourceRecordSet.ResourceRecords = @()
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.9"})
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.10"})

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "www.example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "Rack 5, Positions 1 and 2"
$change2.ResourceRecordSet.Weight = 3
$change2.ResourceRecordSet.TTL = 600
$change2.ResourceRecordSet.ResourceRecords = @()
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.11"})
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.12"})

$params = @{
    HostedZoneId="Z1PA6795UKMFR9"
    ChangeBatch_Comment="This change creates two weighted resource record sets, each of which has two values."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**範例 4：此範例顯示如何建立加權別名資源記錄集，假設 example.com 是您要為其建立加權別名資源紀錄集的網域。SetIdentifier 會區分兩個加權別名資源記錄集。此元素是必要的，因為兩個資源記錄集的 Name 和 Type 元素具有相同的值。Z1111111111111 和 Z3333333333333 是 DNSName 值指定之 ELB 負載平衡器的託管區域 ID 的範例。example-load-balancer-2222222222.us-east-1.elb.amazonaws.com 和 example-load-balancer-4444444444.us-east-1.elb.amazonaws.com 是 Elastic Load Balancing 網域的範例，而 Amazon Route 53 便是從該網域回應對 example.com 的查詢。如需詳細資訊，請參閱 Amazon Route 53 文件。您可以使用 Get-R53Change Cmdlet 輪詢，判斷變更何時完成。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "1"
$change1.ResourceRecordSet.Weight = 3
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-2222222222.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "2"
$change2.ResourceRecordSet.Weight = 1
$change2.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change2.ResourceRecordSet.AliasTarget.HostedZoneId = "Z3333333333333"
$change2.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-4444444444.us-east-1.elb.amazonaws.com."
$change2.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $false

$params = @{
    HostedZoneId="Z5555555555"
    ChangeBatch_Comment="This change batch creates two weighted alias resource record sets. Amazon Route 53 responds to queries for example.com with the first ELB domain 3/4ths of the times and the second one 1/4th of the time."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**範例 5：此範例會建立兩個延遲別名資源記錄集，一個用於美國西部 (奧勒岡) 區域 (us-west-2) 的 ELB 負載平衡器，另一個用於亞太地區 (新加坡) 區域 (ap-southeast-1) 的負載平衡器。如需詳細資訊，請參閱 Amazon Route 53 文件。您可以使用 Get-R53Change Cmdlet 輪詢，判斷變更何時完成。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "Oregon load balancer 1"
$change1.ResourceRecordSet.Region = us-west-2
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-2222222222.us-west-2.elb.amazonaws.com"
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "Singapore load balancer 1"
$change2.ResourceRecordSet.Region = ap-southeast-1
$change2.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change2.ResourceRecordSet.AliasTarget.HostedZoneId = "Z2222222222222"
$change2.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.ap-southeast-1.elb.amazonaws.com"
$change2.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$params = @{
    HostedZoneId="Z5555555555"
    ChangeBatch_Comment="This change batch creates two latency resource record sets, one for the US West (Oregon) region and one for the Asia Pacific (Singapore) region."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ChangeResourceRecordSets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53AccountLimit`
<a name="route-53_GetAccountLimit_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53AccountLimit`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回可使用目前帳戶建立的最大託管區域數目。**  

```
Get-R53AccountLimit -Type MAX_HOSTED_ZONES_BY_OWNER
```
**輸出：**  

```
15
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAccountLimit](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53CheckerIpRanges`
<a name="route-53_GetCheckerIpRanges_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53CheckerIpRanges`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回 Route53 運作狀態檢查程式 CIDR**  

```
Get-R53CheckerIpRanges
```
**輸出：**  

```
15.177.2.0/23
15.177.6.0/23
15.177.10.0/23
15.177.14.0/23
15.177.18.0/23
15.177.22.0/23
15.177.26.0/23
15.177.30.0/23
15.177.34.0/23
15.177.38.0/23
15.177.42.0/23
15.177.46.0/23
15.177.50.0/23
15.177.54.0/23
15.177.58.0/23
15.177.62.0/23
54.183.255.128/26
54.228.16.0/26
54.232.40.64/26
54.241.32.64/26
54.243.31.192/26
54.244.52.192/26
54.245.168.0/26
54.248.220.0/26
54.250.253.192/26
54.251.31.128/26
54.252.79.128/26
54.252.254.192/26
54.255.254.192/26
107.23.255.0/26
176.34.159.192/26
177.71.207.128/26
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetCheckerIpRanges](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53HostedZone`
<a name="route-53_GetHostedZone_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53HostedZone`。

**Tools for PowerShell V5**  
**範例 1：傳回具 ID Z1D633PJN98FT9 之託管區域的詳細資訊。**  

```
Get-R53HostedZone -Id Z1D633PJN98FT9
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53HostedZoneCount`
<a name="route-53_GetHostedZoneCount_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53HostedZoneCount`。

**Tools for PowerShell V5**  
**範例 1：傳回目前 的公有和私有託管區域總數 AWS 帳戶。**  

```
Get-R53HostedZoneCount
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetHostedZoneCount](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53HostedZoneLimit`
<a name="route-53_GetHostedZoneLimit_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53HostedZoneLimit`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回可在指定託管區域中建立之最大記錄數目的限制。**  

```
Get-R53HostedZoneLimit -HostedZoneId Z3MEQ8T7HAAAAF -Type MAX_RRSETS_BY_ZONE
```
**輸出：**  

```
5
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetHostedZoneLimit](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53HostedZoneList`
<a name="route-53_ListHostedZones_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53HostedZoneList`。

**Tools for PowerShell V5**  
**範例 1：輸出所有公有和私有託管區域。**  

```
Get-R53HostedZoneList
```
**範例 2：輸出與具有 ID NZ8X2CISAMPLE 的可重複使用的委派集相關聯的所有託管區域**  

```
Get-R53HostedZoneList -DelegationSetId NZ8X2CISAMPLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListHostedZones](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53HostedZonesByName`
<a name="route-53_ListHostedZonesByName_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53HostedZonesByName`。

**Tools for PowerShell V5**  
**範例 1：依網域名稱，以 ASCII 順序傳回所有公有和私有託管區域。**  

```
Get-R53HostedZonesByName
```
**範例 2：依網域名稱，以 ASCII 順序傳回公有和私有託管區域，從指定的 DNS 名稱開始。**  

```
Get-R53HostedZonesByName -DnsName example2.com
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListHostedZonesByName](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53QueryLoggingConfigList`
<a name="route-53_ListQueryLoggingConfigs_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53QueryLoggingConfigList`。

**Tools for PowerShell V5**  
**範例 1：此範例會傳回與目前 AWS 帳戶相關聯的 DNS 查詢日誌記錄的所有組態。**  

```
Get-R53QueryLoggingConfigList
```
**輸出：**  

```
Id                                   HostedZoneId   CloudWatchLogsLogGroupArn
--                                   ------------   -------------------------
59b0fa33-4fea-4471-a88c-926476aaa40d Z385PDS6EAAAZR arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example1.com:*
ee528e95-4e03-4fdc-9d28-9e24ddaaa063 Z94SJHBV1AAAAZ arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example2.com:*
e38dddda-ceb6-45c1-8cb7-f0ae56aaaa2b Z3MEQ8T7AAA1BF arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example3.com:*
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListQueryLoggingConfigs](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-R53ReusableDelegationSet`
<a name="route-53_GetReusableDelegationSet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-R53ReusableDelegationSet`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取指定之委派集的相關資訊，包括指派給委派集的四個名稱伺服器。**  

```
Get-R53ReusableDelegationSet -Id N23DS9X4AYEAAA
```
**輸出：**  

```
Id                            CallerReference NameServers
--                            --------------- -----------
/delegationset/N23DS9X4AYEAAA testcaller      {ns-545.awsdns-04.net, ns-1264.awsdns-30.org, ns-2004.awsdns-58.co.uk, ns-240.awsdns-30.com}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-R53HostedZone`
<a name="route-53_CreateHostedZone_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-R53HostedZone`。

**Tools for PowerShell V5**  
**範例 1：建立名為 'example.com'，且與可重複使用的委派集相關聯的新託管區域。請注意，您必須為 CallerReference 參數提供一個值，以便在必要時重試請求，而不會有執行兩次操作的風險。由於託管區域是在 VPC 中建立，因此會自動變成私有，而且您不應該設定 -HostedZoneConfig\$1PrivateZone 參數。**  

```
$params = @{
    Name="example.com"
    CallerReference="myUniqueIdentifier"
    HostedZoneConfig_Comment="This is my first hosted zone"
    DelegationSetId="NZ8X2CISAMPLE"
    VPC_VPCId="vpc-1a2b3c4d"
    VPC_VPCRegion="us-east-1"
}

New-R53HostedZone @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-R53QueryLoggingConfig`
<a name="route-53_CreateQueryLoggingConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-R53QueryLoggingConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會為指定的託管區域建立新的 Route53 DNS 查詢日誌記錄組態。Amazon Route53 會將 DNS 查詢日誌發佈至指定的 Cloudwatch 日誌群組。**  

```
New-R53QueryLoggingConfig -HostedZoneId Z3MEQ8T7HAAAAF -CloudWatchLogsLogGroupArn arn:aws:logs:us-east-1:111111111111:log-group:/aws/route53/example.com:*
```
**輸出：**  

```
QueryLoggingConfig                      Location
------------------                      --------
Amazon.Route53.Model.QueryLoggingConfig https://route53.amazonaws.com/2013-04-01/queryloggingconfig/ee5aaa95-4e03-4fdc-9d28-9e24ddaaaaa3
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-R53ReusableDelegationSet`
<a name="route-53_CreateReusableDelegationSet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-R53ReusableDelegationSet`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立一組可重複使用的委派，其中包含 4 個名稱伺服器，可供多個託管區域重複使用。**  

```
New-R53ReusableDelegationSet -CallerReference testcallerreference
```
**輸出：**  

```
DelegationSet                      Location
-------------                      --------
Amazon.Route53.Model.DelegationSet https://route53.amazonaws.com/2013-04-01/delegationset/N23DS9XAAAAAXM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-R53VPCWithHostedZone`
<a name="route-53_AssociateVPCWithHostedZone_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-R53VPCWithHostedZone`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定的 VPC 與私有託管區域相關聯。**  

```
Register-R53VPCWithHostedZone -HostedZoneId Z3MEQ8T7HAAAAF -VPC_VPCId vpc-f1b9aaaa -VPC_VPCRegion us-east-1
```
**輸出：**  

```
Id                     Status  SubmittedAt         Comment
--                     ------  -----------         -------
/change/C3SCAAA633Z6DX PENDING 01/28/2020 19:32:02
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssociateVPCWithHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-R53HostedZone`
<a name="route-53_DeleteHostedZone_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-R53HostedZone`。

**Tools for PowerShell V5**  
**範例 1：刪除具有指定 ID 的託管區域。除非您新增 -Force 切換變數，否則會在命令繼續之前，提示您進行確認。**  

```
Remove-R53HostedZone -Id Z1PA6795UKMFR9
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-R53QueryLoggingConfig`
<a name="route-53_DeleteQueryLoggingConfig_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-R53QueryLoggingConfig`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除 DNS 查詢日誌記錄的指定組態。**  

```
Remove-R53QueryLoggingConfig -Id ee528e95-4e03-4fdc-9d28-9e24daaa20063
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-R53ReusableDelegationSet`
<a name="route-53_DeleteReusableDelegationSet_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-R53ReusableDelegationSet`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的可重複使用委派集。**  

```
Remove-R53ReusableDelegationSet -Id N23DS9X4AYAAAM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-R53VPCFromHostedZone`
<a name="route-53_DisassociateVPCFromHostedZone_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-R53VPCFromHostedZone`。

**Tools for PowerShell V5**  
**範例 1：此範例會取消指定的 VPC 與私有託管區域的關聯。**  

```
Unregister-R53VPCFromHostedZone -HostedZoneId Z3MEQ8T7HAAAAF -VPC_VPCId vpc-f1b9aaaa -VPC_VPCRegion us-east-1
```
**輸出：**  

```
Id                     Status  SubmittedAt         Comment
--                     ------  -----------         -------
/change/C2XFCAAAA9HKZG PENDING 01/28/2020 10:35:55
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisassociateVPCFromHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-R53HostedZoneComment`
<a name="route-53_UpdateHostedZoneComment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-R53HostedZoneComment`。

**Tools for PowerShell V5**  
**範例 1：此命令會更新指定託管區域的註解。**  

```
Update-R53HostedZoneComment -Id Z385PDS6AAAAAR -Comment "This is my first hosted zone"
```
**輸出：**  

```
Id                     : /hostedzone/Z385PDS6AAAAAR
Name                   : example.com.
CallerReference        : C5B55555-7147-EF04-8341-69131E805C89
Config                 : Amazon.Route53.Model.HostedZoneConfig
ResourceRecordSetCount : 9
LinkedService          :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateHostedZoneComment](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon S3 範例
<a name="powershell_s3_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon S3 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Copy-S3Object`
<a name="s3_CopyObject_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Copy-S3Object`。

**Tools for PowerShell V5**  
**範例 1：此命令會將物件"sample.txt" 從儲存貯體 "test-files" 複製到相同的儲存貯體，但具有新索引鍵 "sample-copy.txt"。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -DestinationKey sample-copy.txt
```
**範例 2：此命令會將物件"sample.txt" 從儲存貯體 "test-files" 複製到儲存貯體 "backup-files"，索引鍵為 "sample-copy.txt"。**  

```
Copy-S3Object -BucketName amzn-s3-demo-source-bucket -Key sample.txt -DestinationKey sample-copy.txt -DestinationBucket amzn-s3-demo-destination-bucket
```
**範例 3：此命令會將物件"sample.txt" 從儲存貯體 "test-files" 下載至名為 "local-sample.txt" 的本機檔案。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -LocalFile local-sample.txt
```
**範例 4：將單一物件下載至指定的檔案。下載的檔案位於 c:\$1downloads\$1data\$1archive.zip**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key data/archive.zip -LocalFolder c:\downloads
```
**範例 5：將符合指定索引鍵字首的所有物件下載至本機資料夾。相對索引鍵階層會保留為整體下載位置中的子資料夾。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix data -LocalFolder c:\downloads
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CopyObject](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3Bucket`
<a name="s3_ListBuckets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3Bucket`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回所有 S3 儲存貯體。**  

```
Get-S3Bucket
```
**範例 2：此命令會傳回名為 "test-files" 的儲存貯體**  

```
Get-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListBuckets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketACL`
<a name="s3_GetBucketAcl_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketACL`。

**Tools for PowerShell V5**  
**範例 1： 命令會取得 S3 物件之物件擁有者的詳細資訊。**  

```
(Get-S3BucketACL -BucketName 'amzn-s3-demo-bucket' -Select *).Owner
```
**輸出：**  

```
DisplayName Id
----------- --
testusername      9988776a6554433d22f1100112e334acb45566778899009e9887bd7f66c5f544
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketAcl](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketAccelerateConfiguration`
<a name="s3_GetBucketAccelerateConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketAccelerateConfiguration`。

**Tools for PowerShell V5**  
**範例 1：如果為指定的儲存貯體啟用傳輸加速設定，此命令會傳回已啟用的值。**  

```
Get-S3BucketAccelerateConfiguration -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
Value                                  
-----                                    
Enabled
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketAnalyticsConfiguration`
<a name="s3_GetBucketAnalyticsConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketAnalyticsConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回指定 S3 儲存貯體中名為 'testfilter' 的分析篩選條件詳細資訊。**  

```
Get-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketAnalyticsConfigurationList`
<a name="s3_ListBucketAnalyticsConfigurations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketAnalyticsConfigurationList`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體的前 100 個分析組態。**  

```
Get-S3BucketAnalyticsConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListBucketAnalyticsConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketEncryption`
<a name="s3_GetBucketEncryption_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketEncryption`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回與指定儲存貯體相關聯的所有伺服器端加密規則。**  

```
Get-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketInventoryConfiguration`
<a name="s3_GetBucketInventoryConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketInventoryConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體之名為 'testinventory' 的庫存詳細資訊。**  

```
Get-S3BucketInventoryConfiguration -BucketName 'amzn-s3-demo-bucket' -InventoryId 'testinventory'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketInventoryConfigurationList`
<a name="s3_ListBucketInventoryConfigurations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketInventoryConfigurationList`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體的前 100 個庫存組態。**  

```
Get-S3BucketInventoryConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListBucketInventoryConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketLocation`
<a name="s3_GetBucketLocation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketLocation`。

**Tools for PowerShell V5**  
**範例 1：如果存在限制，此命令會傳回儲存貯體 'amzn-s3-demo-bucket' 的位置限制。**  

```
Get-S3BucketLocation -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
Value
-----
ap-south-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketLocation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketLogging`
<a name="s3_GetBucketLogging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketLogging`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回指定儲存貯體的記錄狀態。**  

```
Get-S3BucketLogging -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
TargetBucketName   Grants TargetPrefix
----------------   ------ ------------
testbucket1        {}     testprefix
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketLogging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketMetricsConfiguration`
<a name="s3_GetBucketMetricsConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketMetricsConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體之名為 'testfilter' 的指標篩選條件詳細資訊。**  

```
Get-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testfilter'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketNotification`
<a name="s3_GetBucketNotification_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketNotification`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取給定儲存貯體的通知組態**  

```
Get-S3BucketNotification -BucketName amzn-s3-demo-bucket | select -ExpandProperty TopicConfigurations
```
**輸出：**  

```
Id   Topic
--   -----
mimo arn:aws:sns:eu-west-1:123456789012:topic-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketNotification](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketPolicy`
<a name="s3_GetBucketPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketPolicy`。

**Tools for PowerShell V5**  
**範例 1：此命令會輸出與給定 S3 儲存貯體相關聯的儲存貯體政策。**  

```
Get-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketPolicyStatus`
<a name="s3_GetBucketPolicyStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketPolicyStatus`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體的政策狀態，其指出儲存貯體是否為公有。**  

```
Get-S3BucketPolicyStatus -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketPolicyStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketReplication`
<a name="s3_GetBucketReplication_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketReplication`。

**Tools for PowerShell V5**  
**範例 1：傳回在名為 'amzn-s3-demo-bucket' 的儲存貯體上設定的複寫組態資訊。**  

```
Get-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketRequestPayment`
<a name="s3_GetBucketRequestPayment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketRequestPayment`。

**Tools for PowerShell V5**  
**範例 1：傳回名為 'amzn-s3-demo-bucket' 之儲存貯體的請求付款組態。根據預設，儲存貯體擁有者會支付從儲存貯體下載的費用。**  

```
Get-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**的 [GetBucketRequestPayment](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketTagging`
<a name="s3_GetBucketTagging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketTagging`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回與給定儲存貯體相關聯的所有標籤。**  

```
Get-S3BucketTagging -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketVersioning`
<a name="s3_GetBucketVersioning_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketVersioning`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回與給定儲存貯體相關的版本控制狀態。**  

```
Get-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketVersioning](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3BucketWebsite`
<a name="s3_GetBucketWebsite_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3BucketWebsite`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體之靜態網站組態的詳細資訊。**  

```
Get-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3CORSConfiguration`
<a name="s3_GetCORSConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3CORSConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回物件，其包含對應至給定 S3 儲存貯體的所有 CORS 組態規則。**  

```
Get-S3CORSConfiguration -BucketName 'amzn-s3-demo-bucket' -Select Configuration.Rules
```
**輸出：**  

```
AllowedMethods : {PUT, POST, DELETE}
AllowedOrigins : {http://www.example1.com}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {*}

AllowedMethods : {PUT, POST, DELETE}
AllowedOrigins : {http://www.example2.com}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {*}

AllowedMethods : {GET}
AllowedOrigins : {*}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetCORSConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3HeadBucket`
<a name="s3_HeadBucket_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3HeadBucket`。

**Tools for PowerShell V5**  
**範例 1：當使用者有權存取現有儲存貯體時，此命令會傳回 HTTP 狀態碼為 200 OK 的輸出。BucketArn 參數僅支援 S3 目錄儲存貯體。**  

```
Get-S3HeadBucket -BucketName amzn-s3-demo-bucket
```
**輸出：**  

```
AccessPointAlias   : False
BucketArn          :
BucketLocationName : 
BucketLocationType : 
BucketRegion       : us-east-2
ResponseMetadata   : Amazon.Runtime.ResponseMetadata
ContentLength      : 0
HttpStatusCode     : OK
```
**範例 2：此命令會針對不存在的儲存貯體擲回 HTTP 狀態碼 NotFound 的錯誤。**  

```
Get-S3HeadBucket -BucketName amzn-s3-non-existing-bucket
```
**輸出：**  

```
Get-S3HeadBucket: Error making request with Error Code NotFound and Http Status Code NotFound. No further error information was returned by the service.
```
**範例 3：對於使用者無權存取的現有儲存貯體，此命令會擲回 HTTP 狀態碼為 Forbidden (禁止) 的錯誤。**  

```
Get-S3HeadBucket -BucketName amzn-s3-no-access-bucket
```
**輸出：**  

```
Get-S3HeadBucket: Error making request with Error Code Forbidden and Http Status Code Forbidden. No further error information was returned by the service.
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [HeadBucket](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3LifecycleConfiguration`
<a name="s3_GetLifecycleConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3LifecycleConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取儲存貯體的生命週期組態。**  

```
Get-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket
```
**輸出：**  

```
Rules
-----
{Remove-in-150-days, Archive-to-Glacier-in-30-days}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3Object`
<a name="s3_ListObjects_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3Object`。

**Tools for PowerShell V5**  
**範例 1：此命令會擷取儲存貯體 "test-files" 中所有項目的相關資訊。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket
```
**範例 2：此命令會從儲存貯體 "test-files" 擷取項目 "sample.txt" 的相關資訊。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt
```
**範例 3：此命令會從儲存貯體 "test-files" 擷取字首為 "sample" 之所有項目的相關資訊。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix sample
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListObjects](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3ObjectACL`
<a name="s3_GetObjectAcl_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3ObjectACL`。

**Tools for PowerShell V5**  
**範例 1： 命令會取得 S3 物件之物件擁有者的詳細資訊。**  

```
(Get-S3ObjectACL -BucketName 'amzn-s3-demo-bucket' -key 'initialize.ps1' -Select *).Owner
```
**輸出：**  

```
DisplayName Id
----------- --
testusername      9988776a6554433d22f1100112e334acb45566778899009e9887bd7f66c5f544
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetObjectAcl](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3ObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3ObjectLockConfiguration`。

**Tools for PowerShell V5**  
**範例 1：如果為給定的 S3 儲存貯體啟用物件鎖定組態，此命令會傳回值 'Enabled'**。  

```
Get-S3ObjectLockConfiguration -BucketName 'amzn-s3-demo-bucket' -Select ObjectLockConfiguration.ObjectLockEnabled
```
**輸出：**  

```
Value
-----
Enabled
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetObjectLockConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3ObjectMetadata`
<a name="s3_GetObjectMetadata_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3ObjectMetadata`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體中金索引鍵為 'ListTrusts.txt' 的物件中繼資料。**  

```
Get-S3ObjectMetadata -BucketName 'amzn-s3-demo-bucket' -Key 'ListTrusts.txt'
```
**輸出：**  

```
Headers                                       : Amazon.S3.Model.HeadersCollection
Metadata                                      : Amazon.S3.Model.MetadataCollection
DeleteMarker                                  : 
AcceptRanges                                  : bytes
ContentRange                                  : 
Expiration                                    : 
RestoreExpiration                             : 
RestoreInProgress                             : False
LastModified                                  : 01/01/2020 08:02:05
ETag                                          : "d000011112a222e333e3bb4ee5d43d21"
MissingMeta                                   : 0
VersionId                                     : null
Expires                                       : 01/01/0001 00:00:00
WebsiteRedirectLocation                       : 
ServerSideEncryptionMethod                    : AES256
ServerSideEncryptionCustomerMethod            : 
ServerSideEncryptionKeyManagementServiceKeyId : 
ReplicationStatus                             : 
PartsCount                                    : 
ObjectLockLegalHoldStatus                     : 
ObjectLockMode                                : 
ObjectLockRetainUntilDate                     : 01/01/0001 00:00:00
StorageClass                                  : 
RequestCharged                                :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetObjectMetadata](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3ObjectRetention`
<a name="s3_GetObjectRetention_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3ObjectRetention`。

**Tools for PowerShell V5**  
**範例 1：命令會傳回模式和日期，直到保留物件為止。**  

```
Get-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetObjectRetention](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3ObjectTagSet`
<a name="s3_GetObjectTagging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3ObjectTagSet`。

**Tools for PowerShell V5**  
**範例 1：範例會傳回與給定 S3 儲存貯體上存在之物件相關聯的標籤。**  

```
Get-S3ObjectTagSet -Key 'testfile.txt' -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
Key  Value
---  -----
test value
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetObjectTagging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3PreSignedURL`
<a name="s3_GetPreSignedURL_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3PreSignedURL`。

**Tools for PowerShell V5**  
**範例 1： 命令會傳回指定金鑰和到期日期的預先簽章 URL。**  

```
Get-S3PreSignedURL -BucketName 'amzn-s3-demo-bucket' -Key 'testkey' -Expires '2023-11-16'
```
**範例 2： 命令會傳回具有指定金鑰和到期日期的目錄儲存貯體的預先簽章 URL。**  

```
[Amazon.AWSConfigsS3]::UseSignatureVersion4 = $true
      Get-S3PreSignedURL -BucketName amzn-s3-demo-bucket--usw2-az1--x-s3 -Key 'testkey' -Expire '2023-11-17'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPreSignedURL](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3PublicAccessBlock`
<a name="s3_GetPublicAccessBlock_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3PublicAccessBlock`。

**Tools for PowerShell V5**  
**範例 1： 命令會傳回給定 S3 儲存貯體的公有存取區塊組態。**  

```
Get-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPublicAccessBlock](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3Version`
<a name="s3_ListVersions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-S3Version`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回給定 S3 儲存貯體中所有物件版本的中繼資料。**  

```
Get-S3Version -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
IsTruncated         : False
KeyMarker           : 
VersionIdMarker     : 
NextKeyMarker       : 
NextVersionIdMarker : 
Versions            : {EC2.txt, EC2MicrosoftWindowsGuide.txt, ListDirectories.json, ListTrusts.json}
Name                : amzn-s3-demo-bucket
Prefix              : 
MaxKeys             : 1000
CommonPrefixes      : {}
Delimiter           :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListVersions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-S3Bucket`
<a name="s3_PutBucket_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-S3Bucket`。

**Tools for PowerShell V5**  
**範例 1：此命令會建立名為 "sample-bucket" 的新私有儲存貯體。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket
```
**範例 2：此命令會建立名為 "sample-bucket" 且具有讀寫權限的新儲存貯體。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket -PublicReadWrite
```
**範例 3：此命令會建立名為 "sample-bucket" 且具有唯讀權限的新儲存貯體。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket -PublicReadOnly
```
**範例 4：此命令會使用 PutBucketConfiguration 建立新的目錄儲存貯體，名為 "amzn-s3-demo-bucket--use1-az5--x-s3"。**  

```
$bucketConfiguration = @{
      BucketInfo = @{
          DataRedundancy = 'SingleAvailabilityZone'
          Type = 'Directory'
      }
      Location = @{
          Name = 'usw2-az1'
          Type = 'AvailabilityZone'
      }
    }
New-S3Bucket -BucketName amzn-s3-demo-bucket--usw2-az1--x-s3 -BucketConfiguration $bucketConfiguration -Region us-west-2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucket](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Read-S3Object`
<a name="s3_GetObject_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Read-S3Object`。

**Tools for PowerShell V5**  
**範例 1：此命令會從儲存貯體 "amzn-s3-demo-bucket" 擷取項目 "sample.txt"，並將其儲存至目前位置中名為 "local-sample.txt" 的檔案。在呼叫此命令之前，檔案 "local-sample.txt" 不需存在。**  

```
Read-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -File local-sample.txt
```
**範例 2：此命令會從儲存貯體 "amzn-s3-demo-bucket" 擷取虛擬目錄 "DIR"，並將其儲存至目前位置中名為 "Local-DIR" 的資料夾。呼叫此命令之前，資料夾 "Local-DIR" 不需存在。**  

```
Read-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix DIR -Folder Local-DIR
```
**範例 3：將所有金鑰以 '.json' 結尾的物件，從儲存貯體名稱具有 'config' 的儲存貯體，下載到指定資料夾中的檔案。物件金鑰用於設定檔案名稱。**  

```
Get-S3Bucket | ? { $_.BucketName -like '*config*' } | Get-S3Object | ? { $_.Key -like '*.json' } | Read-S3Object -Folder C:\ConfigObjects
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetObject](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3Bucket`
<a name="s3_DeleteBucket_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3Bucket`。

**Tools for PowerShell V5**  
**範例 1：此命令會從儲存貯體 'test-files' 移除所有物件和物件版本，然後刪除儲存貯體。繼續之前，此命令會先提示確認。新增 - 強制切換以隱藏確認。請注意，不是空的儲存貯體無法刪除。**  

```
Remove-S3Bucket -BucketName amzn-s3-demo-bucket -DeleteBucketContent
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucket](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketAnalyticsConfiguration`
<a name="s3_DeleteBucketAnalyticsConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketAnalyticsConfiguration`。

**Tools for PowerShell V5**  
**範例 1： 命令會移除給定 S3 儲存貯體中名為 'testfilter' 的分析篩選條件。**  

```
Remove-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketEncryption`
<a name="s3_DeleteBucketEncryption_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketEncryption`。

**Tools for PowerShell V5**  
**範例 1：這會停用針對提供的 S3 儲存貯體啟用的加密。**  

```
Remove-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketEncryption (DeleteBucketEncryption)" on target "s3casetestbucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketInventoryConfiguration`
<a name="s3_DeleteBucketInventoryConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketInventoryConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此命令會移除與給定 S3 儲存貯體對應之名為 'testInventoryName' 的庫存。**  

```
Remove-S3BucketInventoryConfiguration -BucketName 'amzn-s3-demo-bucket' -InventoryId 'testInventoryName'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketInventoryConfiguration (DeleteBucketInventoryConfiguration)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketMetricsConfiguration`
<a name="s3_DeleteBucketMetricsConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketMetricsConfiguration`。

**Tools for PowerShell V5**  
**範例 1： 命令會移除給定 S3 儲存貯體中名為 'testmetrics' 的指標篩選條件。**  

```
Remove-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testmetrics'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketPolicy`
<a name="s3_DeleteBucketPolicy_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketPolicy`。

**Tools for PowerShell V5**  
**範例 1： 命令會移除與給定 S3 儲存貯體相關聯的儲存貯體政策。**  

```
Remove-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketReplication`
<a name="s3_DeleteBucketReplication_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketReplication`。

**Tools for PowerShell V5**  
**範例 1：刪除與名為 'amzn-s3-demo-bucket' 的儲存貯體相關聯的複寫組態。請注意，此操作需要 s3：DeleteReplicationConfiguration 動作的許可權。在繼續操作之前，系統會提示您確認 - 若要隱藏確認，請使用 -Force 切換變數。**  

```
Remove-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketTagging`
<a name="s3_DeleteBucketTagging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketTagging`。

**Tools for PowerShell V5**  
**範例 1：此命令會移除與給定 S3 儲存貯體相關聯的所有標籤。**  

```
Remove-S3BucketTagging -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketTagging (DeleteBucketTagging)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3BucketWebsite`
<a name="s3_DeleteBucketWebsite_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3BucketWebsite`。

**Tools for PowerShell V5**  
**範例 1：此命令會停用給定 S3 儲存貯體的靜態網站託管屬性。**  

```
Remove-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketWebsite (DeleteBucketWebsite)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3CORSConfiguration`
<a name="s3_DeleteCORSConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3CORSConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此命令會移除給定 S3 儲存貯體的 CORS 組態。**  

```
Remove-S3CORSConfiguration -BucketName 'amzn-s3-demo-bucket'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3CORSConfiguration (DeleteCORSConfiguration)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteCORSConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3LifecycleConfiguration`
<a name="s3_DeleteLifecycleConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3LifecycleConfiguration`。

**Tools for PowerShell V5**  
**範例 1： 命令會移除給定 S3 儲存貯體的所有生命週期規則。**  

```
Remove-S3LifecycleConfiguration -BucketName 'amzn-s3-demo-bucket'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3MultipartUpload`
<a name="s3_AbortMultipartUpload_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3MultipartUpload`。

**Tools for PowerShell V5**  
**範例 1：此命令中止 5 天前建立的分段上傳。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -DaysBefore 5
```
**範例 2：此命令中止 2014 年 1 月 2 日之前建立的分段上傳。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -InitiatedDate "Thursday, January 02, 2014"
```
**範例 3：此命令中止 2014 年 1 月 2 日 10:45:37 之前建立的分段上傳。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -InitiatedDate "2014/01/02 10:45:37"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中 [AbortMultipartUpload](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3Object`
<a name="s3_DeleteObjects_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3Object`。

**Tools for PowerShell V5**  
**範例 1：此命令會從儲存貯體 "test-files" 中移除物件"sample.txt"。在執行命令之前，系統會提示您確認；若要隱藏提示，請使用 -Force 切換變數。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt
```
**範例 2：此命令會移除儲存貯體 "test-files" 中物件"sample.txt" 的指定版本，假設儲存貯體已設定為啟用物件版本。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -VersionId HLbxnx6V9omT6AQYVpks8mmFKQcejpqt
```
**範例 3：此命令會將儲存貯體 "test-files" 中的物件"sample1.txt"、"sample2.txt" 和 "sample3.txt" 移除，以成為單一批次操作。無論是刪除成功或錯誤狀態，服務回應都會列出處理的所有索引鍵。若要僅取得無法由服務處理之索引鍵的錯誤，請新增 -ReportErrorsOnly 參數 (也可以使用別名 -Quiet 指定此參數。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -KeyCollection @( "sample1.txt", "sample2.txt", "sample3.txt" )
```
**範例 4：此範例搭配 -KeyCollection 參數使用內嵌表達式，以取得要刪除之物件的索引鍵。Get-S3Object 會傳回 Amazon.S3.Model.S3Object 執行個體的集合，每個執行個體都有一個字串類型的索引鍵成員來識別物件。**  

```
Remove-S3Object -bucketname "amzn-s3-demo-bucket" -KeyCollection (Get-S3Object "test-files" -KeyPrefix "prefix/subprefix" | select -ExpandProperty Key)
```
**範例 5：此範例會取得儲存貯體中具有索引鍵字首「字首/子字首」的所有物件，並將其刪除。請注意，一次只會處理一個傳入物件。對於大型集合，請考慮將集合傳遞至 Cmdlet 的 -InputObject (別名 -S3ObjectCollection) 參數，透過一次服務呼叫來批次執行刪除作業。**  

```
Get-S3Object -BucketName "amzn-s3-demo-bucket" -KeyPrefix "prefix/subprefix" | Remove-S3Object -Force
```
**範例 6：此範例會將代表刪除標記的 Amazon.S3.Model.S3ObjectVersion 執行個體集合傳輸至 Cmdlet，以進行刪除。請注意，一次只會處理一個傳入物件。對於大型集合，請考慮將集合傳遞至 Cmdlet 的 -InputObject (別名 -S3ObjectCollection) 參數，透過一次服務呼叫來批次執行刪除作業。**  

```
(Get-S3Version -BucketName "amzn-s3-demo-bucket").Versions | Where {$_.IsDeleteMarker -eq "True"} | Remove-S3Object -Force
```
**範例 7：此指令碼示範如何透過建構要與 -KeyAndVersionCollection 參數搭配使用的物件陣列，執行一組物件的批次刪除 (在此案例中為刪除標記)**。  

```
$keyVersions = @()
$markers = (Get-S3Version -BucketName $BucketName).Versions | Where {$_.IsDeleteMarker -eq "True"}
foreach ($marker in $markers) { $keyVersions += @{ Key = $marker.Key; VersionId = $marker.VersionId } }
Remove-S3Object -BucketName $BucketName -KeyAndVersionCollection $keyVersions -Force
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteObjects](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3ObjectTagSet`
<a name="s3_DeleteObjectTagging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3ObjectTagSet`。

**Tools for PowerShell V5**  
**範例 1：此命令會移除與給定 S3 儲存貯體中具索引鍵 'testfile.txt' 之物件相關聯的所有標籤。**  

```
Remove-S3ObjectTagSet -Key 'testfile.txt' -BucketName 'amzn-s3-demo-bucket' -Select '^Key'
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3ObjectTagSet (DeleteObjectTagging)" on target "testfile.txt".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
testfile.txt
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteObjectTagging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3PublicAccessBlock`
<a name="s3_DeletePublicAccessBlock_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-S3PublicAccessBlock`。

**Tools for PowerShell V5**  
**範例 1：此命令會關閉給定儲存貯體的封鎖公開存取設定。**  

```
Remove-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket' -Force -Select '^BucketName'
```
**輸出：**  

```
amzn-s3-demo-bucket
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeletePublicAccessBlock](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-S3BucketEncryption`
<a name="s3_PutBucketEncryption_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-S3BucketEncryption`。

**Tools for PowerShell V5**  
**範例 1：此命令會在給定的儲存貯體上使用 Amazon S3 受管金鑰 (SSE-S3)，以啟用預設 AES256 伺服器端加密。 **  

```
$Encryptionconfig = @{ServerSideEncryptionByDefault = @{ServerSideEncryptionAlgorithm = "AES256"}}
Set-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket' -ServerSideEncryptionConfiguration_ServerSideEncryptionRule $Encryptionconfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Test-S3Bucket`
<a name="s3_Test-S3Bucket_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Test-S3Bucket`。

**Tools for PowerShell V5**  
**範例 1：如果有儲存貯體，則此命令會傳回 True，否則傳回 False。即使儲存貯體不屬於使用者，命令也會傳回 True。**  

```
Test-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Test-S3Bucket](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3BucketAccelerateConfiguration`
<a name="s3_PutBucketAccelerateConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3BucketAccelerateConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此命令會使給定 S3 儲存貯體的傳輸加速。**  

```
$statusVal = New-Object Amazon.S3.BucketAccelerateStatus('Enabled')
Write-S3BucketAccelerateConfiguration -BucketName 'amzn-s3-demo-bucket' -AccelerateConfiguration_Status $statusVal
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3BucketNotification`
<a name="s3_PutBucketNotification_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3BucketNotification`。

**Tools for PowerShell V5**  
**範例 1：此範例會設定 S3 事件 ObjectRemovedDelete 的 SNS 主題組態，並啟用給定 s3 儲存貯體的通知**  

```
$topic =  [Amazon.S3.Model.TopicConfiguration] @{
  Id = "delete-event"
  Topic = "arn:aws:sns:eu-west-1:123456789012:topic-1"
  Event = [Amazon.S3.EventType]::ObjectRemovedDelete
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -TopicConfiguration $topic
```
**範例 2：此範例會為傳送至 Lambda 函式的給定儲存貯體，啟用 ObjectCreatedAll 通知。**  

```
$lambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = "s3:ObjectCreated:*"
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:rdplock"
  Id = "ObjectCreated-Lambda"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".pem"}
      )
    }
  }
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -LambdaFunctionConfiguration $lambdaConfig
```
**範例 3：此範例會根據不同的索引鍵尾碼建立 2 個不同的 Lambda 組態，並在單一命令中同時設定兩者。**  

```
#Lambda Config 1

$firstLambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = "s3:ObjectCreated:*"
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifynet"
  Id = "ObjectCreated-dada-ps1"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".ps1"}
      )
    }
  }
}

#Lambda Config 2

$secondlambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = [Amazon.S3.EventType]::ObjectCreatedAll
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifyssm"
  Id = "ObjectCreated-dada-json"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".json"}
      )
    }
  }
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -LambdaFunctionConfiguration $firstLambdaConfig,$secondlambdaConfig
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketNotification](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3BucketReplication`
<a name="s3_PutBucketReplication_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3BucketReplication`。

**Tools for PowerShell V5**  
**範例 1：此範例設定了一個複寫組態，其中的一條規則允許將儲存貯體 'amzn-s3-demo-bucket' 中鍵名字首為 "TaxDocs" 所建立的任何新物件，複製到 'amzn-s3-demo-bucket' 儲存貯體。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Enabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1
}

Write-S3BucketReplication @params
```
**範例 2：此範例設定具有多個規則的複寫組態，可將任何以鍵名字首 "TaxDocs" 或 "OtherDocs" 建立的新物件，複寫至 'amzn-s3-demo-bucket' 儲存貯體。索引鍵字首不得重疊。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Enabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$rule2 = New-Object Amazon.S3.Model.ReplicationRule
$rule2.ID = "Rule-2"
$rule2.Status = "Enabled"
$rule2.Prefix = "OtherDocs"
$rule2.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1,$rule2
}

Write-S3BucketReplication @params
```
**範例 3：此範例會更新指定之儲存貯體上的複寫組態，以停用控制將鍵名字首為 "TaxDocs" 之物件複寫至 'amzn-s3-demo-bucket' 儲存貯體的規則。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Disabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1
}

Write-S3BucketReplication @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3BucketRequestPayment`
<a name="s3_PutBucketRequestPayment_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3BucketRequestPayment`。

**Tools for PowerShell V5**  
**範例 1：更新名為 'amzn-s3-demo-bucket' 之儲存貯體的請求付費組態，如此一來，請求從儲存貯體下載的人員將需支付下載費用。根據預設，儲存貯體擁有者需支付下載費用。若要將請求付費設回預設，請針對 RequestPaymentConfiguration\$1Payer 參數使用 'BucketOwner'。**  

```
Write-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket -RequestPaymentConfiguration_Payer Requester
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketRequestPayment](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3BucketTagging`
<a name="s3_PutBucketTagging_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3BucketTagging`。

**Tools for PowerShell V5**  
**範例 1：此命令會將兩個標籤套用至名為 `cloudtrail-test-2018` 的儲存貯體：一個是索引鍵為 Stage 且值為 Test 的標籤，另一個是索引鍵為 Environment 且值為 Alpha 的標籤。若要驗證標籤是否已新增至儲存貯體，請執行 `Get-S3BucketTagging -BucketName bucket_name`。結果應該會顯示您在第一個命令中套用至儲存貯體的標籤。請注意，`Write-S3BucketTagging` 會覆寫儲存貯體上設定的整個現有標籤。若要新增或刪除個別標籤，請執行資源群組和標記 API Cmdlet，`Add-RGTResourceTag` 和 `Remove-RGTResourceTag`。或者，在 AWS 管理主控台中使用標籤編輯器來管理 S3 儲存貯體標籤。**  

```
Write-S3BucketTagging -BucketName amzn-s3-demo-bucket -TagSet @( @{ Key="Stage"; Value="Test" }, @{ Key="Environment"; Value="Alpha" } )
```
**範例 2：此命令會將名為 `cloudtrail-test-2018` 的儲存貯體傳輸至 `Write-S3BucketTagging` cmdlet。範例會將標籤 Stage:Production 和 Department:Finance 套用至儲存貯體。請注意，`Write-S3BucketTagging` 會覆寫儲存貯體上設定的整個現有標籤。**  

```
Get-S3Bucket -BucketName amzn-s3-demo-bucket | Write-S3BucketTagging -TagSet @( @{ Key="Stage"; Value="Production" }, @{ Key="Department"; Value="Finance" } )
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3BucketVersioning`
<a name="s3_PutBucketVersioning_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3BucketVersioning`。

**Tools for PowerShell V5**  
**範例 1： 命令會啟用給定 S3 儲存貯體的版本控制。**  

```
Write-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket' -VersioningConfig_Status Enabled
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketVersioning](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3BucketWebsite`
<a name="s3_PutBucketWebsite_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3BucketWebsite`。

**Tools for PowerShell V5**  
**範例 1：命令會啟用給定儲存貯體的網站託管，其中索引文件為 'index.html'，錯誤文件為 'error.html'。**  

```
Write-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket' -WebsiteConfiguration_IndexDocumentSuffix 'index.html' -WebsiteConfiguration_ErrorDocument 'error.html'
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3LifecycleConfiguration`
<a name="s3_PutLifecycleConfiguration_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3LifecycleConfiguration`。

**Tools for PowerShell V5**  
**範例 1：此範例會寫入/取代 \$1NewRule 中提供的組態。此組態可確保限制具有給定字首和標籤值的範圍物件。**  

```
$NewRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  @{
			Days=  50
		}
		Id =  "Test-From-Write-cmdlet-1"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands=  @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "non-use"
							"Value" = "yes"
						}
					}
				)
			}
		}
		"Status"= 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 75
		}
	}
    
	Write-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket -Configuration_Rule $NewRule
```
**範例 2：此範例使用篩選條件設定多個規則。\$1ArchiveRule 會將要在 30 天內封存的物件設定為 Glacier，並將 120 天內封存的物件的設定為 DeepArchive。\$1ExpireRule 會針對具有 'py' 字首和 tag:key 'archieved' 設定為 'yes' 的物件，使其目前和先前版本在 150 天內到期。**  

```
$ExpireRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  @{
			Days=  150
		}
		Id =  "Remove-in-150-days"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands=  @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "archived"
							"Value" = "yes"
						}
					}
				)
			}
		}
		Status= 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 150
		}
	}

	$ArchiveRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  $null
		Id =  "Archive-to-Glacier-in-30-days"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands= @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "reviewed"
							"Value" = "yes"
						}
					}
				)
			}
		}
		Status = 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 75
		}
		Transitions = @(
			@{
				Days = 30
				"StorageClass"= 'Glacier'
			},
			@{
				Days = 120
				"StorageClass"= [Amazon.S3.S3StorageClass]::DeepArchive
			}
		)
	}

	Write-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket -Configuration_Rule $ExpireRule,$ArchiveRule
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3Object`
<a name="s3_PutObject_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3Object`。

**Tools for PowerShell V5**  
**範例 1：此命令會將單一檔案 "local-sample.txt" 上傳至 Amazon S3，並在儲存貯體 "test-files" 中建立具索引鍵 "sample.txt" 的物件。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "sample.txt" -File .\local-sample.txt
```
**範例 2：此命令會將單一檔案 "sample.txt" 上傳至 Amazon S3，並在儲存貯體 "test-files" 中建立具索引鍵 "sample.txt" 的物件。如果未提供 -Key 參數，則會將檔案名稱用作 S3 物件索引鍵。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -File .\sample.txt
```
**範例 3：此命令會將單一檔案 "local-sample.txt" 上傳至 Amazon S3，並在儲存貯體 "test-files" 中建立具索引鍵 "prefix/to/sample.txt" 的物件。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "prefix/to/sample.txt" -File .\local-sample.txt
```
**範例 4：此命令會將子目錄 "Scripts" 中的所有檔案上傳至儲存貯體 "test-files"，並將通用索引鍵字首 "SampleScripts" 套用至每個物件。每個上傳的檔案都會有一個索引鍵 "SampleScripts/filename"，其中 'filename' 會有所不同。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder .\Scripts -KeyPrefix SampleScripts\
```
**範例 5：此命令會將本機目錄 "Scripts" 中的所有 \$1.ps1 檔案上傳至儲存貯體 "test-files"，並將通用索引鍵字首 "SampleScripts" 套用至每個物件。每個上傳的檔案都會有一個索引鍵 "SampleScripts/filename.ps1"，其中 'filename' 會有所不同。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder .\Scripts -KeyPrefix SampleScripts\ -SearchPattern *.ps1
```
**範例 6：此命令會建立新的 S3 物件，其中包含索引鍵 'sample.txt' 的指定內容字串。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "sample.txt" -Content "object contents"
```
**範例 7：此命令會上傳指定的檔案 (檔案名稱用作索引鍵)，並將指定的標籤套用至新物件。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -File "sample.txt" -TagSet @{Key="key1";Value="value1"},@{Key="key2";Value="value2"}
```
**範例 8：此命令會以遞迴方式上傳指定的資料夾，並將指定的標籤套用至所有新物件。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder . -KeyPrefix "TaggedFiles" -Recurse -TagSet @{Key="key1";Value="value1"},@{Key="key2";Value="value2"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutObject](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-S3ObjectRetention`
<a name="s3_PutObjectRetention_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-S3ObjectRetention`。

**Tools for PowerShell V5**  
**範例 1： 命令會針對給定 S3 儲存貯體中的 'testfile.txt' 物件啟用控管保留模式，直到「2019 年 12 月 31 日 00:00:00」為止。**  

```
Write-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt' -Retention_Mode GOVERNANCE -Retention_RetainUntilDate "2019-12-31T00:00:00"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutObjectRetention](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Security Hub CSPM 範例
<a name="powershell_securityhub_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Security Hub CSPM 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-SHUBFinding`
<a name="securityhub_GetSHUBFinding_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SHUBFinding`。

**Tools for PowerShell V5**  
**範例 1：此命令會從 Amazon EC2; 服務擷取 Security Hub 調查結果。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.ResourceType = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'PREFIX'
    Value = 'AwsEc2'
}
Get-SHUBFinding -Filter $filter
```
**範例 2：此命令會從 AWS 帳戶 ID 123456789012 擷取 Security Hub 問題清單。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.AwsAccountId = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = '123456789012'
}
Get-SHUBFinding -Filter $filter
```
**範例 3：此命令會擷取標準 "pci-dss" 產生的 Security Hub 調查結果。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.GeneratorId = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'PREFIX'
    Value = 'pci-dss'
}
Get-SHUBFinding -Filter $filter
```
**範例 4：此命令會擷取工作流程狀態為 NOTIFIED 的 Security Hub 重大嚴重性調查結果。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.SeverityLabel = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = 'CRITICAL'
}
$filter.WorkflowStatus = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = 'NOTIFIED'
}
Get-SHUBFinding -Filter $filter
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetFindings](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon SES 範例
<a name="powershell_ses_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon SES 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Get-SESIdentity`
<a name="ses_ListIdentities_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SESIdentity`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回包含特定 AWS 帳戶所有身分 （電子郵件地址和網域） 的清單，無論驗證狀態為何。**  

```
Get-SESIdentity
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListIdentities](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SESSendQuota`
<a name="ses_GetSendQuota_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SESSendQuota`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回使用者目前的傳送限制。**  

```
Get-SESSendQuota
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetSendQuota](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SESSendStatistic`
<a name="ses_GetSendStatistics_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SESSendStatistic`。

**Tools for PowerShell V5**  
**範例 1：此命令會傳回使用者的傳送統計資料。結果是一份資料點清單，代表過去兩週的傳送活動。清單中的每個資料點都包含間隔 15 分鐘的統計資料。**  

```
Get-SESSendStatistic
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetSendStatistics](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon SES API v2 範例
<a name="powershell_sesv2_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon SES API v2 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Send-SES2Email`
<a name="sesv2_SendSES2Email_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Send-SES2Email`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何傳送標準電子郵件訊息。**  

```
Send-SES2Email -FromEmailAddress "sender@example.com" -Destination_ToAddress "recipient@example.com" -Subject_Data "Email Subject" -Text_Data "Email Body"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SendEmail](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon SNS 範例
<a name="powershell_sns_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon SNS 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Publish-SNSMessage`
<a name="sns_Publish_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Publish-SNSMessage`。

**Tools for PowerShell V5**  
**範例 1：此範例示範發佈一則附帶內嵌宣告的單一 MessageAttribute 訊息。**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**範例 2：此範例示範發佈多則預先宣告的 MessageAttributes 訊息。**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Publish](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon SQS 範例
<a name="powershell_sqs_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon SQS 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-SQSPermission`
<a name="sqs_AddPermission_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-SQSPermission`。

**Tools for PowerShell V5**  
**範例 1：此範例允許指定的 從指定的佇列 AWS 帳戶 傳送訊息。**  

```
Add-SQSPermission -Action SendMessage -AWSAccountId 80398EXAMPLE -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddPermission](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Clear-SQSQueue`
<a name="sqs_PurgeQueue_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Clear-SQSQueue`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的佇列刪除所有訊息。**  

```
Clear-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PurgeQueue](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-SQSMessageVisibility`
<a name="sqs_ChangeMessageVisibility_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-SQSMessageVisibility`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定佇列中具有指定接收控點的訊息可見性逾時，變更為 10 小時 (10 小時 \$1 60 分鐘 \$1 60 秒 = 36000 秒)。**  

```
Edit-SQSMessageVisibility -QueueUrl https://sqs.us-east-1.amazonaws.com/8039EXAMPLE/MyQueue -ReceiptHandle AQEBgGDh...J/Iqww== -VisibilityTimeout 36000
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ChangeMessageVisibility](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-SQSMessageVisibilityBatch`
<a name="sqs_ChangeMessageVisibilityBatch_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-SQSMessageVisibilityBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會變更在指定佇列中，具有指定接收控點的 2 則訊息的可見性逾時。第一則訊息的可見性逾時變更為 10 小時 (10 小時 \$1 60 分鐘 \$1 60 秒 = 36000 秒)。第二則訊息的可見性逾時變更為 5 小時 (5 小時 \$1 60 分鐘 \$1 60 秒 = 18000 秒)。**  

```
$changeVisibilityRequest1 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry
$changeVisibilityRequest1.Id = "Request1"
$changeVisibilityRequest1.ReceiptHandle = "AQEBd329...v6gl8Q=="
$changeVisibilityRequest1.VisibilityTimeout = 36000

$changeVisibilityRequest2 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry
$changeVisibilityRequest2.Id = "Request2"
$changeVisibilityRequest2.ReceiptHandle = "AQEBgGDh...J/Iqww=="
$changeVisibilityRequest2.VisibilityTimeout = 18000

Edit-SQSMessageVisibilityBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $changeVisibilityRequest1, $changeVisibilityRequest2
```
**輸出：**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {Request2, Request1}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ChangeMessageVisibilityBatch](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SQSDeadLetterSourceQueue`
<a name="sqs_ListDeadLetterSourceQueues_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SQSDeadLetterSourceQueue`。

**Tools for PowerShell V5**  
**範例 1：此範例會列出依賴指定佇列做為無效字母佇列之任何佇列的 URL。**  

```
Get-SQSDeadLetterSourceQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
**輸出：**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDeadLetterSourceQueues](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SQSQueue`
<a name="sqs_ListQueues_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SQSQueue`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了所有佇列。**  

```
Get-SQSQueue
```
**輸出：**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/AnotherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/DeadLetterQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
**範例 2：此範例列出了以指定名稱開頭的任何佇列。**  

```
Get-SQSQueue -QueueNamePrefix My
```
**輸出：**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListQueues](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SQSQueueAttribute`
<a name="sqs_GetQueueAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SQSQueueAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了指定佇列的所有屬性。**  

```
Get-SQSQueueAttribute -AttributeName All -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**輸出：**  

```
VisibilityTimeout                     : 30
DelaySeconds                          : 0
MaximumMessageSize                    : 262144
MessageRetentionPeriod                : 345600
ApproximateNumberOfMessages           : 0
ApproximateNumberOfMessagesNotVisible : 0
ApproximateNumberOfMessagesDelayed    : 0
CreatedTimestamp                      : 2/11/2015 5:53:35 PM
LastModifiedTimestamp                 : 12/29/2015 2:23:17 PM
QueueARN                              : arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue
Policy                                : {"Version":"2012-10-17",		 	 	 "Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/SQSDefaultPolicy","Statement":[{"Sid":"Sid14
                                        495134224EX","Effect":"Allow","Principal":{"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80
                                        398EXAMPLE:MyQueue","Condition":{"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}},{"Sid":
                                        "SendMessagesFromMyQueue","Effect":"Allow","Principal":{"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":"
                                        arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue"}]}
Attributes                            : {[QueueArn, arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue], [ApproximateNumberOfMessages, 0], 
                                        [ApproximateNumberOfMessagesNotVisible, 0], [ApproximateNumberOfMessagesDelayed, 0]...}
```
**範例 2：此範例僅單獨列出指定佇列的指定屬性。**  

```
Get-SQSQueueAttribute -AttributeName MaximumMessageSize, VisibilityTimeout -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**輸出：**  

```
VisibilityTimeout                     : 30
DelaySeconds                          : 0
MaximumMessageSize                    : 262144
MessageRetentionPeriod                : 345600
ApproximateNumberOfMessages           : 0
ApproximateNumberOfMessagesNotVisible : 0
ApproximateNumberOfMessagesDelayed    : 0
CreatedTimestamp                      : 2/11/2015 5:53:35 PM
LastModifiedTimestamp                 : 12/29/2015 2:23:17 PM
QueueARN                              : arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue
Policy                                : {"Version":"2012-10-17",		 	 	 "Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/SQSDefaultPolicy","Statement":[{"Sid":"Sid14
                                        495134224EX","Effect":"Allow","Principal":{"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80
                                        398EXAMPLE:MyQueue","Condition":{"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}},{"Sid":
                                        "SendMessagesFromMyQueue","Effect":"Allow","Principal":{"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":"
                                        arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue"}]}
Attributes                            : {[MaximumMessageSize, 262144], [VisibilityTimeout, 30]}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetQueueAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SQSQueueUrl`
<a name="sqs_GetQueueUrl_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SQSQueueUrl`。

**Tools for PowerShell V5**  
**範例 1：此範例列出具有指定名稱的佇列 URL。**  

```
Get-SQSQueueUrl -QueueName MyQueue
```
**輸出：**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetQueueUrl](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-SQSQueue`
<a name="sqs_CreateQueue_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-SQSQueue`。

**Tools for PowerShell V5**  
**範例 1：此範例會以指定名稱建立佇列。**  

```
New-SQSQueue -QueueName MyQueue
```
**輸出：**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateQueue](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Receive-SQSMessage`
<a name="sqs_ReceiveMessage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Receive-SQSMessage`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了指定之佇列最多可接收後續 10 則訊息的資訊。如果有指定之訊息屬性，則該資訊將會包含這些屬性的值。**  

```
Receive-SQSMessage -AttributeName SenderId, SentTimestamp -MessageAttributeName StudentName, StudentGrade -MessageCount 10 -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**輸出：**  

```
Attributes             : {[SenderId, AIDAIAZKMSNQ7TEXAMPLE], [SentTimestamp, 1451495923744]}
Body                   : Information about John Doe's grade.
MD5OfBody              : ea572796e3c231f974fe75d89EXAMPLE
MD5OfMessageAttributes : 48c1ee811f0fe7c4e88fbe0f5EXAMPLE
MessageAttributes      : {[StudentGrade, Amazon.SQS.Model.MessageAttributeValue], [StudentName, Amazon.SQS.Model.MessageAttributeValue]}
MessageId              : 53828c4b-631b-469b-8833-c093cEXAMPLE
ReceiptHandle          : AQEBpfGp...20Q5cg==
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ReceiveMessage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SQSMessage`
<a name="sqs_DeleteMessage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SQSMessage`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的佇列，刪除具有指定接收控點的訊息。**  

```
Remove-SQSMessage -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -ReceiptHandle AQEBd329...v6gl8Q==
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteMessage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SQSMessageBatch`
<a name="sqs_DeleteMessageBatch_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SQSMessageBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的佇列，刪除具有指定接收控點的 2 則訊息。**  

```
$deleteMessageRequest1 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry
$deleteMessageRequest1.Id = "Request1"
$deleteMessageRequest1.ReceiptHandle = "AQEBX2g4...wtJSQg=="

$deleteMessageRequest2 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry
$deleteMessageRequest2.Id = "Request2"
$deleteMessageRequest2.ReceiptHandle = "AQEBqOVY...KTsLYg=="

Remove-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $deleteMessageRequest1, $deleteMessageRequest2
```
**輸出：**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {Request1, Request2}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteMessageBatch](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SQSPermission`
<a name="sqs_RemovePermission_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SQSPermission`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的佇列中，移除具有指定標籤的許可設定。**  

```
Remove-SQSPermission -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemovePermission](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SQSQueue`
<a name="sqs_DeleteQueue_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SQSQueue`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的佇列。**  

```
Remove-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteQueue](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Send-SQSMessage`
<a name="sqs_SendMessage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Send-SQSMessage`。

**Tools for PowerShell V5**  
**範例 1：此範例會將具有指定屬性和訊息內文的訊息，傳送至指定的佇列，其中訊息傳遞延遲了 10 秒。**  

```
$cityAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Send-SQSMessage -DelayInSeconds 10 -MessageAttributes $messageAttributes -MessageBody "Information about the largest city in Any Region." -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**輸出：**  

```
MD5OfMessageAttributes              MD5OfMessageBody                    MessageId                                          
----------------------              ----------------                    ---------                                          
1d3e51347bc042efbdf6dda31EXAMPLE    51b0a3256d59467f973009b73EXAMPLE    c35fed8f-c739-4d0c-818b-1820eEXAMPLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SendMessage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Send-SQSMessageBatch`
<a name="sqs_SendMessageBatch_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Send-SQSMessageBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例會將 2 則具有指定屬性和訊息內文的訊息，傳送至指定的佇列。第一則訊息的傳遞延遲 15 秒，第二則訊息延遲 10 秒。**  

```
$student1NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student1NameAttributeValue.DataType = "String"
$student1NameAttributeValue.StringValue = "John Doe"

$student1GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student1GradeAttributeValue.DataType = "Number"
$student1GradeAttributeValue.StringValue = "89"

$student2NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student2NameAttributeValue.DataType = "String"
$student2NameAttributeValue.StringValue = "Jane Doe"

$student2GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student2GradeAttributeValue.DataType = "Number"
$student2GradeAttributeValue.StringValue = "93"

$message1 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry 
$message1.DelaySeconds = 15
$message1.Id = "FirstMessage"
$message1.MessageAttributes.Add("StudentName", $student1NameAttributeValue)
$message1.MessageAttributes.Add("StudentGrade", $student1GradeAttributeValue)
$message1.MessageBody = "Information about John Doe's grade."

$message2 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry 
$message2.DelaySeconds = 10
$message2.Id = "SecondMessage"
$message2.MessageAttributes.Add("StudentName", $student2NameAttributeValue)
$message2.MessageAttributes.Add("StudentGrade", $student2GradeAttributeValue)
$message2.MessageBody = "Information about Jane Doe's grade."

Send-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $message1, $message2
```
**輸出：**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {FirstMessage, SecondMessage}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SendMessageBatch](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Set-SQSQueueAttribute`
<a name="sqs_SetQueueAttributes_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Set-SQSQueueAttribute`。

**Tools for PowerShell V5**  
**範例 1：此範例示範如何設定將佇列訂閱至 SNS 主題的政策。當發佈訊息到主題，會傳送訊息至已訂閱的佇列。**  

```
# 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 -AttributeName "QueueArn").QueueARN

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

# set the policy
Set-SQSQueueAttribute -QueueUrl $qurl -Attribute @{ Policy=$policy }
```
**範例 2：此範例會設定指定之佇列的指定屬性。**  

```
Set-SQSQueueAttribute -Attribute @{"DelaySeconds" = "10"; "MaximumMessageSize" = "131072"} -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SetQueueAttributes](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS STS 使用 Tools for PowerShell V5 的範例
<a name="powershell_sts_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS STS。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Convert-STSAuthorizationMessage`
<a name="sts_DecodeAuthorizationMessage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Convert-STSAuthorizationMessage`。

**Tools for PowerShell V5**  
**範例 1：解碼回應請求時傳回的所提供編碼訊息內容中包含的額外資訊。會對額外資訊進行編碼，因為授權狀態的詳細資訊可能構成請求該動作的使用者不應看到的特權資訊。**  

```
Convert-STSAuthorizationMessage -EncodedMessage "...encoded message..."
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DecodeAuthorizationMessage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-STSFederationToken`
<a name="sts_GetFederationToken_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-STSFederationToken`。

**Tools for PowerShell V5**  
**範例 1：使用 "Bob" 作為聯合身分使用者的名稱，請求有效期為一小時的聯合權杖。此名稱可用於參考資源型政策 (例如 Amazon S3 儲存貯體政策) 中的聯合身分使用者名稱。提供的 JSON 格式的 IAM 政策用於縮小 IAM 使用者可用的許可範圍。提供的政策授予的許可不得超過授予給請求使用者的許可，根據傳遞的政策和 IAM 使用者政策的交集，聯合身分使用者的最終許可是最具限制性的集合。**  

```
Get-STSFederationToken -Name "Bob" -Policy "...JSON policy..." -DurationInSeconds 3600
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetFederationToken](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-STSSessionToken`
<a name="sts_GetSessionToken_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-STSSessionToken`。

**Tools for PowerShell V5**  
**範例 1：傳回 `Amazon.RuntimeAWSCredentials` 執行個體，其中包含有效期為設定時間段的臨時憑證。從目前 Shell 預設值中推斷出用於請求臨時憑證的憑證。若要指定其他憑證，請使用 -ProfileName 或 -AccessKey/-SecretKey 參數。**  

```
Get-STSSessionToken
```
**輸出：**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**範例 2：傳回 `Amazon.RuntimeAWSCredentials` 執行個體，其中包含有效期為一小時的臨時憑證。從指定的設定檔中取得用於提出請求的憑證。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile
```
**輸出：**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**範例 3：使用在設定檔 'myprofilename' 中指定其憑證的帳戶關聯的 MFA 裝置識別碼和裝置提供的值，傳回 `Amazon.RuntimeAWSCredentials` 執行個體，其中包含有效期為一小時的臨時憑證。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile -SerialNumber YourMFADeviceSerialNumber -TokenCode 123456
```
**輸出：**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetSessionToken](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Use-STSRole`
<a name="sts_AssumeRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Use-STSRole`。

**Tools for PowerShell V5**  
**範例 1：傳回一組臨時登入資料 （存取金鑰、私密金鑰和工作階段字符），可用於存取請求使用者通常無法存取 AWS 的資源一小時。傳回的憑證擁有所擔任角色之存取政策和提供的政策所允許的許可 (您無法使用提供的政策來授予超過所擔任角色之存取政策所定義的許可)。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600
```
**範例 2：傳回一組臨時憑證，有效期為一小時，這些憑證擁有所擔任角色之存取政策中定義的相同許可。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600
```
**範例 3：傳回一組臨時憑證，提供序號，以及與用於執行 cmdlet 之使用者憑證相關聯的 MFA 產生的權杖。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"
```
**範例 4：傳回一組臨時憑證，這些臨時憑證擔任了客戶帳戶中定義的角色。對於第三方可以擔任的每個角色，客戶帳戶必須使用識別符來建立角色，必須在每次擔任角色時在 -ExternalId 參數中傳遞該識別符。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssumeRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Use-STSWebIdentityRole`
<a name="sts_AssumeRoleWithWebIdentity_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Use-STSWebIdentityRole`。

**Tools for PowerShell V5**  
**範例 1：針對已使用 Login with Amazon 身分提供程式進行身分驗證的使用者，傳回一組臨時憑證，有效期為一小時。憑證會擔任與角色 ARN 所識別角色相關聯的存取政策。或者，您可以將 JSON 政策傳遞至 -Policy 參數，以進一步改進存取許可 (您授予的許可不得超過與角色相關聯的許可中可用的許可)。提供給 -WebIdentityToken 的值是身分提供程式傳回的唯一使用者識別符。**  

```
Use-STSWebIdentityRole -DurationInSeconds 3600 -ProviderId "www.amazon.com" -RoleSessionName "app1" -RoleArn "arn:aws:iam::123456789012:role/FederatedWebIdentityRole" -WebIdentityToken "Atza...DVI0r1"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/powershell/v5/reference)。

# 支援 使用 Tools for PowerShell V5 的範例
<a name="powershell_support_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 支援。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-ASACommunicationToCase`
<a name="support_AddCommunicationToCase_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-ASACommunicationToCase`。

**Tools for PowerShell V5**  
**範例 1：將電子郵件通訊的內文新增至指定的案例。**  

```
Add-ASACommunicationToCase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -CommunicationBody "Some text about the case"
```
**範例 2：將電子郵件通訊的內文新增至指定的案例，再加上電子郵件副本行中包含的一或多個電子郵件地址。**  

```
Add-ASACommunicationToCase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -CcEmailAddress @("email1@address.com", "email2@address.com") -CommunicationBody "Some text about the case"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddCommunicationToCase](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASACase`
<a name="support_DescribeCases_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASACase`。

**Tools for PowerShell V5**  
**範例 1：傳回所有支援案例的詳細資訊。**  

```
Get-ASACase
```
**範例 2：傳回自指定日期和時間以來，所有支援案例的詳細資訊。**  

```
Get-ASACase -AfterTime "2013-09-10T03:06Z"
```
**範例 3：傳回前 10 個支援案例的詳細資訊，包括已解決的案例。**  

```
Get-ASACase -MaxResult 10 -IncludeResolvedCases $true
```
**範例 4：傳回單一指定之支援案例的詳細資訊。**  

```
Get-ASACase -CaseIdList "case-12345678910-2013-c4c1d2bf33c5cf47"
```
**範例 5：傳回指定之支援案例的詳細資訊。**  

```
Get-ASACase -CaseIdList @("case-12345678910-2013-c4c1d2bf33c5cf47", "case-18929034710-2011-c4fdeabf33c5cf47")
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeCases](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASACommunication`
<a name="support_DescribeCommunications_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASACommunication`。

**Tools for PowerShell V5**  
**範例 1：傳回指定案例的所有通訊。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
**範例 2：針對指定的案例，傳回自 2012 年 1 月 1 日 UTC 午夜以來的所有通訊。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -AfterTime "2012-01-10T00:00Z"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeCommunications](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASAService`
<a name="support_DescribeServices_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASAService`。

**Tools for PowerShell V5**  
**範例 1：傳回所有可用的服務代碼、名稱和類別。**  

```
Get-ASAService
```
**範例 2：使用指定的代碼，傳回服務的名稱和類別。**  

```
Get-ASAService -ServiceCodeList "amazon-cloudfront"
```
**範例 3：傳回指定服務代碼的名稱和類別。**  

```
Get-ASAService -ServiceCodeList @("amazon-cloudfront", "amazon-cloudwatch")
```
**範例 4：傳回指定服務代碼的名稱和類別 (日文)。目前支援英文 ("en") 和日文 ("ja") 語言代碼。**  

```
Get-ASAService -ServiceCodeList @("amazon-cloudfront", "amazon-cloudwatch") -Language "ja"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASASeverityLevel`
<a name="support_DescribeSeverityLevels_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASASeverityLevel`。

**Tools for PowerShell V5**  
**範例 1：傳回可指派給 AWS 支援案例的嚴重性等級清單。**  

```
Get-ASASeverityLevel
```
**範例 2：傳回可指派給 AWS 支援案例的嚴重性等級清單。層級名稱以日文傳回。**  

```
Get-ASASeverityLevel -Language "ja"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeSeverityLevels](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASATrustedAdvisorCheck`
<a name="support_DescribeTrustedAdvisorChecks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASATrustedAdvisorCheck`。

**Tools for PowerShell V5**  
**範例 1：傳回 Trusted Advisor 檢查的集合。您必須指定語言參數，其可接受英文輸出 "en"，或日文輸出 "ja"。**  

```
Get-ASATrustedAdvisorCheck -Language "en"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTrustedAdvisorChecks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASATrustedAdvisorCheckRefreshStatus`
<a name="support_DescribeTrustedAdvisorCheckRefreshStatuses_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASATrustedAdvisorCheckRefreshStatus`。

**Tools for PowerShell V5**  
**範例 1：傳回指定之檢查的重新整理請求的目前狀態。Request-ASATrustedAdvisorCheckRefresh 可用來請求重新整理檢查的狀態資訊。**  

```
Get-ASATrustedAdvisorCheckRefreshStatus -CheckId @("checkid1", "checkid2")
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTrustedAdvisorCheckRefreshStatuses](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASATrustedAdvisorCheckResult`
<a name="support_DescribeTrustedAdvisorCheckResult_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASATrustedAdvisorCheckResult`。

**Tools for PowerShell V5**  
**範例 1：傳回 Trusted Advisor 檢查的結果。可使用 Get-ASATrustedAdvisorChecks 取得可用的 Trusted Advisor 檢查清單。輸出是檢查的整體狀態、上次執行檢查的時間戳記，以及特定檢查的唯一 checkid。若要以日文顯示輸出結果，可新增 -Language "ja" 參數。**  

```
Get-ASATrustedAdvisorCheckResult -CheckId "checkid1"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTrustedAdvisorCheckResult](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-ASATrustedAdvisorCheckSummary`
<a name="support_DescribeTrustedAdvisorCheckSummaries_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-ASATrustedAdvisorCheckSummary`。

**Tools for PowerShell V5**  
**範例 1：傳回指定之 Trusted Advisor 檢查的最新摘要。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId "checkid1"
```
**範例 2：傳回指定之 Trusted Advisor 檢查的最新摘要。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId @("checkid1", "checkid2")
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTrustedAdvisorCheckSummaries](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-ASACase`
<a name="support_CreateCase_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-ASACase`。

**Tools for PowerShell V5**  
**範例 1：在 AWS 支援中心建立新案例。可使用 Get-ASAService cmdlet 取得 -ServiceCode 和 -CategoryCode 參數的值。可使用 Get-ASASeverityLevel cmdlet 取得 -SeverityCode 參數的值。-IssueType 參數值可以是 "customer-service" 或 "technical"。如果成功，則會輸出 AWS 支援案例編號。預設以英文處理案例，若要使用日文，則需新增 -Language "ja" 參數。-ServiceCode、-CategoryCode、-Subject 和 -CommunicationBody 參數是強制性的。**  

```
New-ASACase -ServiceCode "amazon-cloudfront" -CategoryCode "APIs" -SeverityCode "low" -Subject "subject text" -CommunicationBody "description of the case" -CcEmailAddress @("email1@domain.com", "email2@domain.com") -IssueType "technical"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateCase](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Request-ASATrustedAdvisorCheckRefresh`
<a name="support_RefreshTrustedAdvisorCheck_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Request-ASATrustedAdvisorCheckRefresh`。

**Tools for PowerShell V5**  
**範例 1：請求重新整理指定的 Trusted Advisor 檢查。**  

```
Request-ASATrustedAdvisorCheckRefresh -CheckId "checkid1"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RefreshTrustedAdvisorCheck](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Resolve-ASACase`
<a name="support_ResolveCase_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Resolve-ASACase`。

**Tools for PowerShell V5**  
**範例 1：傳回指定案例的初始狀態，以及呼叫解決案例完成後的目前狀態。**  

```
Resolve-ASACase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ResolveCase](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Systems Manager 範例
<a name="powershell_ssm_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Systems Manager 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Add-SSMResourceTag`
<a name="ssm_AddTagsToResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Add-SSMResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例示範使用新標籤更新維護時段。如果命令成功，則無輸出訊息。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
$option1 = @{Key="Stack";Value=@("Production")}
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $option1
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立每個標籤。如果命令成功，則無輸出訊息。**  

```
$tag1 = New-Object Amazon.SimpleSystemsManagement.Model.Tag
$tag1.Key = "Stack"
$tag1.Value = "Production"
		
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $tag1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AddTagsToResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-SSMDocumentPermission`
<a name="ssm_ModifyDocumentPermission_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-SSMDocumentPermission`。

**Tools for PowerShell V5**  
**範例 1：此範例將文件的「共用」許可新增至所有帳戶。如果命令成功，則無輸出訊息。**  

```
Edit-SSMDocumentPermission -Name "RunShellScript" -PermissionType "Share" -AccountIdsToAdd all
```
**範例 2：此範例將文件的「共用」許可新增至特定帳戶。如果命令成功，則無輸出訊息。**  

```
Edit-SSMDocumentPermission -Name "RunShellScriptNew" -PermissionType "Share" -AccountIdsToAdd "123456789012"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMActivation`
<a name="ssm_DescribeActivations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMActivation`。

**Tools for PowerShell V5**  
**範例 1：此範例提供有關您帳戶中啟用的詳細資訊。**  

```
Get-SSMActivation
```
**輸出：**  

```
ActivationId        : 08e51e79-1e36-446c-8e63-9458569c1363
CreatedDate         : 3/1/2017 12:01:51 AM
DefaultInstanceName : MyWebServers
Description         :
ExpirationDate      : 3/2/2017 12:01:51 AM
Expired             : False
IamRole             : AutomationRole
RegistrationLimit   : 10
RegistrationsCount  : 0
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeActivations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAssociation`
<a name="ssm_DescribeAssociation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAssociation`。

**Tools for PowerShell V5**  
**範例 1：此範例說明執行個體與文件之間的關聯。**  

```
Get-SSMAssociation -InstanceId "i-0000293ffd8c57862" -Name "AWS-UpdateSSMAgent"
```
**輸出：**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temp_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAssociation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAssociationExecution`
<a name="ssm_DescribeAssociationExecutions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAssociationExecution`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回所提供關聯 ID 的執行**  

```
Get-SSMAssociationExecution -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**輸出：**  

```
AssociationId         : 123a45a0-c678-9012-3456-78901234db5e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 123a45a0-c678-9012-3456-78901234db5e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=4}
Status                : Success
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAssociationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAssociationExecutionTarget`
<a name="ssm_DescribeAssociationExecutionTargets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAssociationExecutionTarget`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示資源 ID 及其執行狀態，它們是關聯執行目標的一部分**  

```
Get-SSMAssociationExecutionTarget -AssociationId 123a45a0-c678-9012-3456-78901234db5e -ExecutionId 123a45a0-c678-9012-3456-78901234db5e | Select-Object ResourceId, Status
```
**輸出：**  

```
ResourceId           Status
----------           ------
i-0b1b2a3456f7a890b  Success
i-01c12a45d6fc7a89f  Success
i-0a1caf234f56d7dc8  Success
i-012a3fd45af6dbcfe  Failed
i-0ddc1df23c4a5fb67  Success
```
**範例 2：此命令會檢查自昨天以來特定自動化的特定執行，其中關聯有命令文件。它會進一步檢查關聯執行是否失敗，如果是，則會顯示該執行的命令調用詳細資訊以及執行個體 ID**  

```
$AssociationExecution= Get-SSMAssociationExecutionTarget -AssociationId 1c234567-890f-1aca-a234-5a678d901cb0 -ExecutionId 12345ca12-3456-2345-2b45-23456789012 | 
    Where-Object {$_.LastExecutionDate -gt (Get-Date -Hour 00 -Minute 00).AddDays(-1)} 

foreach ($execution in $AssociationExecution) {
    if($execution.Status -ne 'Success'){
        Write-Output "There was an issue executing the association $($execution.AssociationId) on $($execution.ResourceId)"
        Get-SSMCommandInvocation -CommandId $execution.OutputSource.OutputSourceId -Detail:$true | Select-Object -ExpandProperty CommandPlugins
    }
}
```
**輸出：**  

```
There was an issue executing the association 1c234567-890f-1aca-a234-5a678d901cb0 on i-0a1caf234f56d7dc8


Name                   : aws:runPowerShellScript
Output                 : 
                         ----------ERROR-------
                         failed to run commands: exit status 1
OutputS3BucketName     : 
OutputS3KeyPrefix      : 
OutputS3Region         : eu-west-1
ResponseCode           : 1
ResponseFinishDateTime : 5/29/2019 11:04:49 AM
ResponseStartDateTime  : 5/29/2019 11:04:49 AM
StandardErrorUrl       : 
StandardOutputUrl      : 
Status                 : Failed
StatusDetails          : Failed
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAssociationExecutionTargets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAssociationList`
<a name="ssm_ListAssociations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAssociationList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了執行個體的所有關聯。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
$filter1 = @{Key="InstanceId";Value=@("i-0000293ffd8c57862")}
Get-SSMAssociationList -AssociationFilterList $filter1
```
**輸出：**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**範例 2：此範例列出了組態文件的所有關聯。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
$filter2 = @{Key="Name";Value=@("AWS-UpdateSSMAgent")}
Get-SSMAssociationList -AssociationFilterList $filter2
```
**輸出：**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**範例 3：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立每個篩選條件。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.AssociationFilter
$filter1.Key = "InstanceId"
$filter1.Value = "i-0000293ffd8c57862"

Get-SSMAssociationList -AssociationFilterList $filter1
```
**輸出：**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAssociations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAssociationVersionList`
<a name="ssm_ListAssociationVersions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAssociationVersionList`。

**Tools for PowerShell V5**  
**範例 1：此範例示範擷取所提供之關聯的所有版本。**  

```
Get-SSMAssociationVersionList -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**輸出：**  

```
AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    :
AssociationVersion : 2
ComplianceSeverity :
CreatedDate        : 3/12/2019 9:21:01 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression :
Targets            : {InstanceIds}

AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    : test-case-1234567890
AssociationVersion : 1
ComplianceSeverity :
CreatedDate        : 3/2/2019 8:53:29 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression : rate(30minutes)
Targets            : {InstanceIds}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListAssociationVersions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAutomationExecution`
<a name="ssm_GetAutomationExecution_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAutomationExecution`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示自動化執行的詳細資訊。**  

```
Get-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
**輸出：**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
FailureMessage            : Step launchInstance failed maximum allowed times. You are not authorized to perform this operation. Encoded
                            authorization failure message: B_V2QyyN7NhSZQYpmVzpEc4oSnj2GLTNYnXUHsTbqJkNMoDgubmbtthLmZyaiUYekORIrA42-fv1x-04q5Fjff6glh
                            Yb6TI5b0GQeeNrpwNvpDzmO-PSR1swlAbg9fdM9BcNjyrznspUkWpuKu9EC1Ou6v3OXU1KC9nZ7mPlWMFZNkSioQqpwWEvMw-GZktsQzm67qOhUhBNOLWYhbS
                            pkfiqzY-5nw3S0obx30fhd3EJa5O_-GjV_a0nFXQJa70ik40bFOrEh3MtCSbrQT6--DvFy_FQ8TKvkIXadyVskeJI84XOF5WmA60f1pi5GI08i-nRfZS6oDeU
                            gELBjjoFKD8s3L2aI0B6umWVxnQOjqhQRxwJ53b54sZJ2PW3v_mtg9-q0CK0ezS3xfh_y0ilaUGOAZG-xjQFuvU_JZedWpla3xi-MZsmblAifBI
                            (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID:
                            6a002f94-ba37-43fd-99e6-39517715fce5)
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
Parameters                : {[AutomationAssumeRole, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [InstanceIamRole,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [SourceAmiId,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
StepExecutions            : {launchInstance, updateOSSoftware, stopInstance, createImage...}
```
**範例 2：此範例列出了指定自動化執行 ID 的步驟詳細資訊**  

```
Get-SSMAutomationExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object -ExpandProperty StepExecutions | Select-Object StepName, Action, StepStatus, ValidNextSteps
```
**輸出：**  

```
StepName                  Action                  StepStatus ValidNextSteps
--------                  ------                  ---------- --------------
LaunchInstance            aws:runInstances        Success    {OSCompatibilityCheck}
OSCompatibilityCheck      aws:runCommand          Success    {RunPreUpdateScript}
RunPreUpdateScript        aws:runCommand          Success    {UpdateEC2Config}
UpdateEC2Config           aws:runCommand          Cancelled  {}
UpdateSSMAgent            aws:runCommand          Pending    {}
UpdateAWSPVDriver         aws:runCommand          Pending    {}
UpdateAWSEnaNetworkDriver aws:runCommand          Pending    {}
UpdateAWSNVMe             aws:runCommand          Pending    {}
InstallWindowsUpdates     aws:runCommand          Pending    {}
RunPostUpdateScript       aws:runCommand          Pending    {}
RunSysprepGeneralize      aws:runCommand          Pending    {}
StopInstance              aws:changeInstanceState Pending    {}
CreateImage               aws:createImage         Pending    {}
TerminateInstance         aws:changeInstanceState Pending    {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAutomationExecutionList`
<a name="ssm_DescribeAutomationExecutions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAutomationExecutionList`。

**Tools for PowerShell V5**  
**範例 1：此範例說明與帳戶關聯的所有作用中和已終止的自動化執行。**  

```
Get-SSMAutomationExecutionList
```
**輸出：**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutedBy                : admin
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
LogFile                   :
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
```
**範例 2：此範例顯示具有 AutomationExecutionStatus 而非 "Success" 之執行的 ExecutionID、文件、執行開始/結束時間戳記**  

```
Get-SSMAutomationExecutionList | Where-Object AutomationExecutionStatus -ne "Success" | Select-Object AutomationExecutionId, DocumentName, AutomationExecutionStatus, ExecutionStartTime, ExecutionEndTime | Format-Table -AutoSize
```
**輸出：**  

```
AutomationExecutionId                DocumentName                            AutomationExecutionStatus ExecutionStartTime   ExecutionEndTime
---------------------                ------------                            ------------------------- ------------------   ----------------
e1d2bad3-4567-8901-ae23-456c7c8901be AWS-UpdateWindowsAmi                    Cancelled                 4/16/2019 5:37:04 AM 4/16/2019 5:47:29 AM
61234567-a7f8-90e1-2b34-567b8bf9012c Fixed-UpdateAmi                         Cancelled                 4/16/2019 5:33:04 AM 4/16/2019 5:40:15 AM
91234d56-7e89-0ac1-2aee-34ea5d6a7c89 AWS-UpdateWindowsAmi                    Failed                    4/16/2019 5:22:46 AM 4/16/2019 5:27:29 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAutomationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAutomationStepExecution`
<a name="ssm_DescribeAutomationStepExecutions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAutomationStepExecution`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示有關自動化工作流程中所有作用中和已終止之步驟執行的資訊。**  

```
Get-SSMAutomationStepExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object StepName, Action, StepStatus
```
**輸出：**  

```
StepName                  Action                  StepStatus
--------                  ------                  ----------
LaunchInstance            aws:runInstances        Success
OSCompatibilityCheck      aws:runCommand          Success
RunPreUpdateScript        aws:runCommand          Success
UpdateEC2Config           aws:runCommand          Cancelled
UpdateSSMAgent            aws:runCommand          Pending
UpdateAWSPVDriver         aws:runCommand          Pending
UpdateAWSEnaNetworkDriver aws:runCommand          Pending
UpdateAWSNVMe             aws:runCommand          Pending
InstallWindowsUpdates     aws:runCommand          Pending
RunPostUpdateScript       aws:runCommand          Pending
RunSysprepGeneralize      aws:runCommand          Pending
StopInstance              aws:changeInstanceState Pending
CreateImage               aws:createImage         Pending
TerminateInstance         aws:changeInstanceState Pending
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAutomationStepExecutions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMAvailablePatch`
<a name="ssm_DescribeAvailablePatches_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMAvailablePatch`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得適用於 Windows Server 2012 的所有可用修補程式，這些修補程式的 MSRC 嚴重性為「關鍵」。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
$filter1 = @{Key="PRODUCT";Values=@("WindowsServer2012")}
$filter2 = @{Key="MSRC_SEVERITY";Values=@("Critical")}

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**輸出：**  

```
Classification : SecurityUpdates
ContentUrl     : https://support.microsoft.com/en-us/kb/2727528
Description    : A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain control
                 over it. You can help protect your system by installing this update from Microsoft. After you install this update, you may have to
                 restart your system.
Id             : 1eb507be-2040-4eeb-803d-abc55700b715
KbNumber       : KB2727528
Language       : All
MsrcNumber     : MS12-072
MsrcSeverity   : Critical
Product        : WindowsServer2012
ProductFamily  : Windows
ReleaseDate    : 11/13/2012 6:00:00 PM
Title          : Security Update for Windows Server 2012 (KB2727528)
Vendor         : Microsoft
...
```
**範例 2：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立每個篩選條件。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "PRODUCT"
$filter1.Values = "WindowsServer2012"
$filter2 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter2.Key = "MSRC_SEVERITY"
$filter2.Values = "Critical"

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**範例 3：此範例示範擷取過去 20 天內發行並適用於符合 WindowsServer2019 的產品的所有更新**  

```
Get-SSMAvailablePatch | Where-Object ReleaseDate -ge (Get-Date).AddDays(-20) | Where-Object Product -eq "WindowsServer2019" | Select-Object ReleaseDate, Product, Title
```
**輸出：**  

```
ReleaseDate         Product           Title
-----------         -------           -----
4/9/2019 5:00:12 PM WindowsServer2019 2019-04 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4493478)
4/9/2019 5:00:06 PM WindowsServer2019 2019-04 Cumulative Update for Windows Server 2019 for x64-based Systems (KB4493509)
4/2/2019 5:00:06 PM WindowsServer2019 2019-03 Servicing Stack Update for Windows Server 2019 for x64-based Systems (KB4493510)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeAvailablePatches](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMCommand`
<a name="ssm_ListCommands_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMCommand`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了所請求的所有命令。**  

```
Get-SSMCommand
```
**輸出：**  

```
CommandId          : 4b75a163-d39a-4d97-87c9-98ae52c6be35
Comment            : Apply association with id at update time: 4cc73e42-d5ae-4879-84f8-57e09c0efcd0
CompletedCount     : 1
DocumentName       : AWS-RefreshAssociation
ErrorCount         : 0
ExpiresAfter       : 2/24/2017 3:19:08 AM
InstanceIds        : {i-0cb2b964d3e14fd9f}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName :
OutputS3KeyPrefix  :
OutputS3Region     :
Parameters         : {[associationIds, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 2/24/2017 3:18:08 AM
ServiceRole        :
Status             : Success
StatusDetails      : Success
TargetCount        : 1
Targets            : {}
```
**範例 2：此範例示範取得特定命令的狀態。**  

```
Get-SSMCommand -CommandId "4b75a163-d39a-4d97-87c9-98ae52c6be35"
```
**範例 3：此範例示範擷取在 2019-04-01T00:00:00Z 之後調用的所有 SSM 命令**  

```
Get-SSMCommand -Filter @{Key="InvokedAfter";Value="2019-04-01T00:00:00Z"} | Select-Object CommandId, DocumentName, Status, RequestedDateTime | Sort-Object -Property RequestedDateTime -Descending
```
**輸出：**  

```
CommandId                            DocumentName               Status    RequestedDateTime
---------                            ------------               ------    -----------------
edb1b23e-456a-7adb-aef8-90e-012ac34f AWS-RunPowerShellScript    Cancelled 4/16/2019 5:45:23 AM
1a2dc3fb-4567-890d-a1ad-234b5d6bc7d9 AWS-ConfigureAWSPackage    Success   4/6/2019 9:19:42 AM
12c3456c-7e90-4f12-1232-1234f5b67893 KT-Retrieve-Cloud-Type-Win Failed    4/2/2019 4:13:07 AM
fe123b45-240c-4123-a2b3-234bdd567ecf AWS-RunInspecChecks        Failed    4/1/2019 2:27:31 PM
1eb23aa4-567d-4123-12a3-4c1c2ab34561 AWS-RunPowerShellScript    Success   4/1/2019 1:05:55 PM
1c2f3bb4-ee12-4bc1-1a23-12345eea123e AWS-RunInspecChecks        Failed    4/1/2019 11:13:09 AM
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListCommands](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMCommandInvocation`
<a name="ssm_ListCommandInvocations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMCommandInvocation`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了命令的所有調用。**  

```
Get-SSMCommandInvocation -CommandId "b8eac879-0541-439d-94ec-47a80d554f44" -Detail $true
```
**輸出：**  

```
CommandId          : b8eac879-0541-439d-94ec-47a80d554f44
CommandPlugins     : {aws:runShellScript}
Comment            : IP config
DocumentName       : AWS-RunShellScript
InstanceId         : i-0cb2b964d3e14fd9f
InstanceName       :
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
RequestedDateTime  : 2/22/2017 8:13:16 PM
ServiceRole        :
StandardErrorUrl   :
StandardOutputUrl  :
Status             : Success
StatusDetails      : Success
TraceOutput        :
```
**範例 2：此範例列出了用於調用命令 ID 為 e1eb2e3c-ed4c-5123-45c1-234f5612345f 的 CommandPlugins**  

```
Get-SSMCommandInvocation -CommandId e1eb2e3c-ed4c-5123-45c1-234f5612345f -Detail:$true | Select-Object -ExpandProperty CommandPlugins
```
**輸出：**  

```
Name                   : aws:runPowerShellScript
Output                 : Completed 17.7 KiB/17.7 KiB (40.1 KiB/s) with 1 file(s) remainingdownload: s3://dd-aess-r-ctmer/KUMO.png to ..\..\programdata\KUMO.png
                         kumo available

OutputS3BucketName     :
OutputS3KeyPrefix      :
OutputS3Region         : eu-west-1
ResponseCode           : 0
ResponseFinishDateTime : 4/3/2019 11:53:23 AM
ResponseStartDateTime  : 4/3/2019 11:53:21 AM
StandardErrorUrl       :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListCommandInvocations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMCommandInvocationDetail`
<a name="ssm_GetCommandInvocation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMCommandInvocationDetail`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示執行個體上所執行之命令的詳細資訊。**  

```
Get-SSMCommandInvocationDetail -InstanceId "i-0cb2b964d3e14fd9f" -CommandId "b8eac879-0541-439d-94ec-47a80d554f44"
```
**輸出：**  

```
CommandId              : b8eac879-0541-439d-94ec-47a80d554f44
Comment                : IP config
DocumentName           : AWS-RunShellScript
ExecutionElapsedTime   : PT0.004S
ExecutionEndDateTime   : 2017-02-22T20:13:16.651Z
ExecutionStartDateTime : 2017-02-22T20:13:16.651Z
InstanceId             : i-0cb2b964d3e14fd9f
PluginName             : aws:runShellScript
ResponseCode           : 0
StandardErrorContent   :
StandardErrorUrl       :
StandardOutputContent  :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetCommandInvocation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMComplianceItemList`
<a name="ssm_ListComplianceItems_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMComplianceItemList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了指定資源 ID 和類型的合規項目清單，篩選合規類型為「關聯」**  

```
Get-SSMComplianceItemList -ResourceId i-1a2caf345f67d0dc2 -ResourceType ManagedInstance -Filter @{Key="ComplianceType";Values="Association"}
```
**輸出：**  

```
ComplianceType   : Association
Details          : {[DocumentName, AWS-GatherSoftwareInventory], [DocumentVersion, 1]}
ExecutionSummary : Amazon.SimpleSystemsManagement.Model.ComplianceExecutionSummary
Id               : 123a45a1-c234-1234-1245-67891236db4e
ResourceId       : i-1a2caf345f67d0dc2
ResourceType     : ManagedInstance
Severity         : UNSPECIFIED
Status           : COMPLIANT
Title            :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMComplianceSummaryList`
<a name="ssm_ListComplianceSummaries_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMComplianceSummaryList`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回所有合規類型的合規與不合規資源計數摘要。**  

```
Get-SSMComplianceSummaryList
```
**輸出：**  

```
ComplianceType CompliantSummary                                      NonCompliantSummary
-------------- ----------------                                      -------------------
FleetTotal     Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Association    Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Custom:InSpec  Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Patch          Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMConnectionStatus`
<a name="ssm_GetConnectionStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMConnectionStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例示範擷取執行個體的 Session Manager 連線狀態，以判斷執行個體是否已連線並準備好接收 Session Manager 連線。**  

```
Get-SSMConnectionStatus -Target i-0a1caf234f12d3dc4
```
**輸出：**  

```
Status    Target
------    ------
Connected i-0a1caf234f12d3dc4
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMDefaultPatchBaseline`
<a name="ssm_GetDefaultPatchBaseline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMDefaultPatchBaseline`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示預設修補基準。**  

```
Get-SSMDefaultPatchBaseline
```
**輸出：**  

```
arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMDeployablePatchSnapshotForInstance`
<a name="ssm_GetDeployablePatchSnapshotForInstance_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMDeployablePatchSnapshotForInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示執行個體所用之修補基準的目前快照。此命令必須使用執行個體憑證從執行個體執行。為確保它使用執行個體憑證，範例會將 `Amazon.Runtime.InstanceProfileAWSCredentials` 物件傳遞至憑證參數。**  

```
$credentials = [Amazon.Runtime.InstanceProfileAWSCredentials]::new()
Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f" -Credentials $credentials
```
**輸出：**  

```
InstanceId          SnapshotDownloadUrl
----------          -------------------
i-0cb2b964d3e14fd9f https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...1692/4681775b-098f-4435...
```
**範例 2：此範例顯示如何取得完整的 SnapshotDownloadUrl。此命令必須使用執行個體憑證從執行個體執行。為確保它使用執行個體憑證，此範例會將 PowerShell 工作階段設定為使用 `Amazon.Runtime.InstanceProfileAWSCredentials` 物件。**  

```
Set-AWSCredential -Credential ([Amazon.Runtime.InstanceProfileAWSCredentials]::new())
(Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f").SnapshotDownloadUrl
```
**輸出：**  

```
https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDeployablePatchSnapshotForInstance](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMDocument`
<a name="ssm_GetDocument_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMDocument`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回文件的內容。**  

```
Get-SSMDocument -Name "RunShellScript"
```
**輸出：**  

```
Content
-------
{...
```
**範例 2：此範例顯示文件的完整內容。**  

```
(Get-SSMDocument -Name "RunShellScript").Content
{
   "schemaVersion":"2.0",
   "description":"Run an updated script",
   "parameters":{
      "commands":{
         "type":"StringList",
         "description":"(Required) Specify a shell script or a command to run.",
         "minItems":1,
         "displayType":"textarea"
      }
   },
   "mainSteps":[
      {
         "action":"aws:runShellScript",
         "name":"runShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      },
      {
         "action":"aws:runPowerShellScript",
         "name":"runPowerShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      }
   ]
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetDocument](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMDocumentDescription`
<a name="ssm_DescribeDocument_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMDocumentDescription`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回文件的相關資訊。**  

```
Get-SSMDocumentDescription -Name "RunShellScript"
```
**輸出：**  

```
CreatedDate     : 2/24/2017 5:25:13 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 123456789012
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Active
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDocument](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMDocumentList`
<a name="ssm_ListDocuments_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMDocumentList`。

**Tools for PowerShell V5**  
**範例 1：列出帳戶中的所有組態文件。**  

```
Get-SSMDocumentList
```
**輸出：**  

```
DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ApplyPatchBaseline
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureAWSPackage
Owner           : Amazon
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 2.0

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureCloudWatch
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2
...
```
**範例 2：此範例示範擷取名稱符合 "Platform" 的所有自動化文件**  

```
Get-SSMDocumentList -DocumentFilterList @{Key="DocumentType";Value="Automation"} | Where-Object Name -Match "Platform"
```
**輸出：**  

```
DocumentFormat  : JSON
DocumentType    : Automation
DocumentVersion : 7
Name            : KT-Get-Platform
Owner           : 987654123456
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 0.3
Tags            : {}
TargetType      :
VersionName     :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDocuments](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMDocumentPermission`
<a name="ssm_DescribeDocumentPermission_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMDocumentPermission`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了文件的所有版本。**  

```
Get-SSMDocumentVersionList -Name "RunShellScript"
```
**輸出：**  

```
CreatedDate          DocumentVersion IsDefaultVersion Name
-----------          --------------- ---------------- ----
2/24/2017 5:25:13 AM 1               True             RunShellScript
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMDocumentVersionList`
<a name="ssm_ListDocumentVersions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMDocumentVersionList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了文件的所有版本。**  

```
Get-SSMDocumentVersionList -Name "AWS-UpdateSSMAgent"
```
**輸出：**  

```
CreatedDate       : 6/1/2021 5:19:10 PM
DocumentFormat    : JSON
DocumentVersion   : 1
IsDefaultVersion  : True
Name              : AWS-UpdateSSMAgent
Status            : Active
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListDocumentVersions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMEffectiveInstanceAssociationList`
<a name="ssm_DescribeEffectiveInstanceAssociations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMEffectiveInstanceAssociationList`。

**Tools for PowerShell V5**  
**範例 1：此範例說明執行個體的有效關聯。**  

```
Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5
```
**輸出：**  

```
AssociationId                        Content
-------------                        -------
d8617c07-2079-4c18-9847-1655fc2698b0 {...
```
**範例 2：此範例顯示執行個體有效關聯的內容。**  

```
(Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5).Content
```
**輸出：**  

```
{
    "schemaVersion": "1.2",
    "description": "Update the Amazon SSM Agent to the latest version or specified version.",
    "parameters": {
        "version": {
            "default": "",
            "description": "(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agen
t will be updated to the latest version.",
            "type": "String"
        },
        "allowDowngrade": {
            "default": "false",
            "description": "(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set
 to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.",
            "type": "String",
            "allowedValues": [
                "true",
                "false"
            ]
        }
    },
    "runtimeConfig": {
        "aws:updateSsmAgent": {
            "properties": [
                {
                "agentName": "amazon-ssm-agent",
                "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json",
                "allowDowngrade": "{{ allowDowngrade }}",
                "targetVersion": "{{ version }}"
                }
            ]
        }
    }
}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEffectiveInstanceAssociations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMEffectivePatchesForPatchBaseline`
<a name="ssm_DescribeEffectivePatchesForPatchBaseline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMEffectivePatchesForPatchBaseline`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了所有修補基準，結果清單上限為 1。**  

```
Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1
```
**輸出：**  

```
Patch                                      PatchStatus
-----                                      -----------
Amazon.SimpleSystemsManagement.Model.Patch Amazon.SimpleSystemsManagement.Model.PatchStatus
```
**範例 2：此範例顯示所有修補基準的修補程式狀態，結果清單上限為 1。**  

```
(Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1).PatchStatus
```
**輸出：**  

```
ApprovalDate          DeploymentStatus
------------          ----------------
12/21/2010 6:00:00 PM APPROVED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeEffectivePatchesForPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInstanceAssociationsStatus`
<a name="ssm_DescribeInstanceAssociationsStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInstanceAssociationsStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示執行個體關聯的詳細資訊。**  

```
Get-SSMInstanceAssociationsStatus -InstanceId "i-0000293ffd8c57862"
```
**輸出：**  

```
AssociationId    : d8617c07-2079-4c18-9847-1655fc2698b0
DetailedStatus   : Pending
DocumentVersion  : 1
ErrorCode        :
ExecutionDate    : 2/20/2015 8:31:11 AM
ExecutionSummary : temp_status_change
InstanceId       : i-0000293ffd8c57862
Name             : AWS-UpdateSSMAgent
OutputUrl        :
Status           : Pending
```
**範例 2：此範例檢查指定執行個體 ID 的執行個體關聯狀態，並進一步顯示這些關聯的執行狀態**  

```
Get-SSMInstanceAssociationsStatus -InstanceId i-012e3cb4df567e8aa | ForEach-Object {Get-SSMAssociationExecution -AssociationId .AssociationId}
```
**輸出：**  

```
AssociationId         : 512a34a5-c678-1234-1234-12345678db9e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 512a34a5-c678-1234-1234-12345678db9e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=9}
Status                : Success
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstanceAssociationsStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInstanceInformation`
<a name="ssm_DescribeInstanceInformation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInstanceInformation`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示每個執行個體的詳細資訊。**  

```
Get-SSMInstanceInformation
```
**輸出：**  

```
ActivationId                           :
AgentVersion                           : 2.0.672.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : ip-172-31-44-222.us-west-2.compute.internal
IamRole                                :
InstanceId                             : i-0cb2b964d3e14fd9f
IPAddress                              : 172.31.44.222
IsLatestVersion                        : True
LastAssociationExecutionDate           : 2/24/2017 3:18:09 AM
LastPingDateTime                       : 2/24/2017 3:35:03 AM
LastSuccessfulAssociationExecutionDate : 2/24/2017 3:18:09 AM
Name                                   :
PingStatus                             : ConnectionLost
PlatformName                           : Amazon Linux AMI
PlatformType                           : Linux
PlatformVersion                        : 2016.09
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**範例 2：此範例示範如何使用 -Filter 參數，僅篩選 區域中`us-east-1`具有 `AgentVersion`之 的 AWS Systems Manager 執行個體的結果`2.2.800.0`。InstanceInformation API 參考主題中提供了有效的 -Filter 鍵值清單 (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformation.html\$1systemsmanager-Type-InstanceInformation-ActivationId)。**  

```
$Filters = @{
    Key="AgentVersion"
    Values="2.2.800.0"
}
Get-SSMInstanceInformation -Region us-east-1 -Filter $Filters
```
**輸出：**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.01
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.02
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**範例 3：此範例示範如何使用 -InstanceInformationFilterList 參數，將結果篩選為 `Windows`或 區域中`us-east-1``PlatformTypes`的 AWS Systems Manager 執行個體`Linux`。InstanceInformation API 參考主題中提供了有效的 -InstanceInformationFilterList 鍵值清單 (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformationFilter.html)。**  

```
$Filters = @{
   Key="PlatformTypes"
   ValueSet=("Windows","Linux")
}
Get-SSMInstanceInformation -Region us-east-1 -InstanceInformationFilterList $Filters
```
**輸出：**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.27
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Ubuntu Server 18.04 LTS
PlatformType                           : Linux
PlatformVersion                        : 18.04
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.100
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**範例 4：此範例列出了 ssm 受管執行個體，並將 InstanceId、PingStatus、LastPingDateTime 和 PlatformName 匯出至 csv 檔案。**  

```
Get-SSMInstanceInformation | Select-Object InstanceId, PingStatus, LastPingDateTime, PlatformName | Export-Csv Instance-details.csv -NoTypeInformation
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstanceInformation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInstancePatch`
<a name="ssm_DescribeInstancePatches_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInstancePatch`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得執行個體的修補程式合規性詳細資訊。**  

```
Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstancePatches](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInstancePatchState`
<a name="ssm_DescribeInstancePatchStates_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInstancePatchState`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得一個執行個體的修補程式摘要狀態。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407"
```
**範例 2：此範例示範取得兩個執行個體的修補程式摘要狀態。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407","i-09a618aec652973a9"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstancePatchStates](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInstancePatchStatesForPatchGroup`
<a name="ssm_DescribeInstancePatchStatesForPatchGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInstancePatchStatesForPatchGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得修補程式群組中每個執行個體的修補程式摘要狀態。**  

```
Get-SSMInstancePatchStatesForPatchGroup -PatchGroup "Production"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeInstancePatchStatesForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInventory`
<a name="ssm_GetInventory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInventory`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得庫存的自訂中繼資料。**  

```
Get-SSMInventory
```
**輸出：**  

```
Data                                                                                  Id
----                                                                                  --
{[AWS:InstanceInformation, Amazon.SimpleSystemsManagement.Model.InventoryResultItem]} i-0cb2b964d3e14fd9f
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetInventory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInventoryEntriesList`
<a name="ssm_ListInventoryEntries_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInventoryEntriesList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了執行個體的所有自訂庫存項目。**  

```
Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo"
```
**輸出：**  

```
CaptureTime   : 2016-08-22T10:01:01Z
Entries       : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,System.String]}
InstanceId    : i-0cb2b964d3e14fd9f
NextToken     :
SchemaVersion : 1.0
TypeName      : Custom:RackInfo
```
**範例 2：此範例列出了詳細資訊。**  

```
(Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo").Entries
```
**輸出：**  

```
Key          Value
---          -----
RackLocation Bay B/Row C/Rack D/Shelf E
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListInventoryEntries](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInventoryEntryList`
<a name="ssm_Get-SSMInventoryEntryList_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInventoryEntryList`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取執行個體的 `AWS:Network` 類型庫存項目。**  

```
Get-SSMInventoryEntryList -InstanceId mi-088dcb0ecea37b076 -TypeName AWS:Network | Select-Object -ExpandProperty Entries
```
**輸出：**  

```
Key        Value
---        -----
DHCPServer 172.31.11.2
DNSServer  172.31.0.1
Gateway    172.31.11.2
IPV4       172.31.11.222
IPV6       fe12::3456:7da8:901a:12a3
MacAddress 1A:23:4E:5B:FB:67
Name       Amazon Elastic Network Adapter
SubnetMask 255.255.240.0
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Get-SSMInventoryEntryList](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMInventorySchema`
<a name="ssm_GetInventorySchema_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMInventorySchema`。

**Tools for PowerShell V5**  
**範例 1：此範例傳回帳戶的庫存類型名稱清單。**  

```
Get-SSMInventorySchema
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetInventorySchema](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMLatestEC2Image`
<a name="ssm_Get-SSMLatestEC2Image_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMLatestEC2Image`。

**Tools for PowerShell V5**  
**範例 1：此範例會列出所有最新的 Windows AMI。**  

```
PS Get-SSMLatestEC2Image -Path ami-windows-latest
```
**輸出：**  

```
Name                                                                    Value
----                                                                    -----
Windows_Server-2008-R2_SP1-English-64Bit-SQL_2012_SP4_Express           ami-0e5ddd288daff4fab
Windows_Server-2012-R2_RTM-Chinese_Simplified-64Bit-Base                ami-0c5ea64e6bec1cb50
Windows_Server-2012-R2_RTM-Chinese_Traditional-64Bit-Base               ami-09775eff0bf8c113d
Windows_Server-2012-R2_RTM-Dutch-64Bit-Base                             ami-025064b67e28cf5df
...
```
**範例 2：此範例會擷取 us-west-2 區域的特定 Amazon Linux 映像的 AMI ID。**  

```
PS Get-SSMLatestEC2Image -Path ami-amazon-linux-latest -ImageName amzn-ami-hvm-x86_64-ebs -Region us-west-2
```
**輸出：**  

```
ami-09b92cd132204c704
```
**範例 3：此範例會列出符合指定之萬用字元表達式的所有最新 Windows AMI。**  

```
Get-SSMLatestEC2Image -Path ami-windows-latest -ImageName *Windows*2019*English*
```
**輸出：**  

```
Name                                                     Value
----                                                     -----
Windows_Server-2019-English-Full-SQL_2017_Web            ami-085e9d27da5b73a42
Windows_Server-2019-English-STIG-Core                    ami-0bfd85c29148c7f80
Windows_Server-2019-English-Full-SQL_2019_Web            ami-02099560d7fb11f20
Windows_Server-2019-English-Full-SQL_2016_SP2_Standard   ami-0d7ae2d81c07bd598
...
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Get-SSMLatestEC2Image](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindow`
<a name="ssm_GetMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得有關維護時段的詳細資訊。**  

```
Get-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d"
```
**輸出：**  

```
AllowUnassociatedTargets : False
CreatedDate              : 2/20/2017 6:14:05 PM
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
ModifiedDate             : 2/20/2017 6:14:05 PM
Name                     : TestMaintWin
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowExecution`
<a name="ssm_GetMaintenanceWindowExecution_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowExecution`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了作為維護時段執行的一部分執行之任務的資訊。**  

```
Get-SSMMaintenanceWindowExecution -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**輸出：**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
TaskIds           : {ac0c6ae1-daa3-4a89-832e-d384503b6586}
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetMaintenanceWindowExecution](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowExecutionList`
<a name="ssm_DescribeMaintenanceWindowExecutions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowExecutionList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了維護時段的所有執行。**  

```
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d"
```
**輸出：**  

```
EndTime           : 2/20/2017 6:30:17 PM
StartTime         : 2/20/2017 6:30:16 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
WindowExecutionId : 6f3215cf-4101-4fa0-9b7b-9523269599c7
WindowId          : mw-03eb9db42890fb82d
```
**範例 2：此範例列出了指定日期之前維護時段的所有執行。**  

```
$option1 = @{Key="ExecutedBefore";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
**範例 3：此範例列出了指定日期之後維護時段的所有執行。**  

```
$option1 = @{Key="ExecutedAfter";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMaintenanceWindowExecutions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowExecutionTask`
<a name="ssm_GetMaintenanceWindowExecutionTask_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowExecutionTask`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了有關屬於維護時段執行之任務的資訊。**  

```
Get-SSMMaintenanceWindowExecutionTask -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**輸出：**  

```
EndTime           : 2/21/2017 4:00:35 PM
MaxConcurrency    : 1
MaxErrors         : 1
Priority          : 10
ServiceRole       : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The maximum error count was exceeded.
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskParameters    : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskPara
                    meterValueExpression]}
Type              : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetMaintenanceWindowExecutionTask](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowExecutionTaskInvocationList`
<a name="ssm_DescribeMaintenanceWindowExecutionTaskInvocations_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowExecutionTaskInvocationList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了作為維護時段執行的一部分執行之任務的調用。**  

```
Get-SSMMaintenanceWindowExecutionTaskInvocationList -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**輸出：**  

```
EndTime           : 2/21/2017 4:00:34 PM
ExecutionId       :
InvocationId      : e274b6e1-fe56-4e32-bd2a-8073c6381d8b
OwnerInformation  :
Parameters        : {"documentName":"AWS-RunShellScript","instanceIds":["i-0000293ffd8c57862"],"parameters":{"commands":["df"]},"maxConcurrency":"1",
                    "maxErrors":"1"}
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The instance IDs list contains an invalid entry.
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
WindowTargetId    :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMaintenanceWindowExecutionTaskInvocations](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowExecutionTaskList`
<a name="ssm_DescribeMaintenanceWindowExecutionTasks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowExecutionTaskList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了與維護時段執行關聯的任務。**  

```
Get-SSMMaintenanceWindowExecutionTaskList -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**輸出：**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : SUCCESS
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskType          : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMaintenanceWindowExecutionTasks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowList`
<a name="ssm_DescribeMaintenanceWindows_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了帳戶的所有維護時段。**  

```
Get-SSMMaintenanceWindowList
```
**輸出：**  

```
Cutoff   : 1
Duration : 4
Enabled  : True
Name     : My-First-Maintenance-Window
WindowId : mw-06d59c1a07c022145
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMaintenanceWindows](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowTarget`
<a name="ssm_DescribeMaintenanceWindowTargets_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowTarget`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了維護時段的所有目標。**  

```
Get-SSMMaintenanceWindowTarget -WindowId "mw-06cf17cbefcb4bf4f"
```
**輸出：**  

```
OwnerInformation : Single instance
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : 350d44e6-28cc-44e2-951f-4b2c985838f6

OwnerInformation : Two instances in a list
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : e078a987-2866-47be-bedd-d9cf49177d3a
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMaintenanceWindowTargets](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindowTaskList`
<a name="ssm_DescribeMaintenanceWindowTasks_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMMaintenanceWindowTaskList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了維護時段的所有任務。**  

```
Get-SSMMaintenanceWindowTaskList -WindowId "mw-06cf17cbefcb4bf4f"
```
**輸出：**  

```
LoggingInfo    :
MaxConcurrency : 1
MaxErrors      : 1
Priority       : 10
ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
Targets        : {InstanceIds}
TaskArn        : AWS-RunShellScript
TaskParameters : {[commands, Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression]}
Type           : RUN_COMMAND
WindowId       : mw-06cf17cbefcb4bf4f
WindowTaskId   : a23e338d-ff30-4398-8aa3-09cd052ebf17
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeMaintenanceWindowTasks](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMParameterHistory`
<a name="ssm_GetParameterHistory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMParameterHistory`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了參數的值歷史記錄。**  

```
Get-SSMParameterHistory -Name "Welcome"
```
**輸出：**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:55:25 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
Value            : helloWorld
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetParameterHistory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMParameterList`
<a name="ssm_DescribeParameters_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMParameterList`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了所有參數。**  

```
Get-SSMParameterList
```
**輸出：**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:58:23 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeParameters](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMParameterValue`
<a name="ssm_GetParameters_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMParameterValue`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了參數的多個值。**  

```
Get-SSMParameterValue -Name "Welcome"
```
**輸出：**  

```
InvalidParameters Parameters
----------------- ----------
{}                {Welcome}
```
**範例 2：此範例列出了值的詳細資訊。**  

```
(Get-SSMParameterValue -Name "Welcome").Parameters
```
**輸出：**  

```
Name    Type   Value
----    ----   -----
Welcome String Good day, Sunshine!
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetParameters](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMPatchBaseline`
<a name="ssm_DescribePatchBaselines_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMPatchBaseline`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了所有修補基準。**  

```
Get-SSMPatchBaseline
```
**輸出：**  

```
BaselineDescription                                             BaselineId                                                            BaselineName
-------------------                                             ----------                                                            ------------
Default Patch Baseline Provided by AWS.                         arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultP...
Baseline containing all updates approved for production systems pb-045f10b4f382baeda                                                  Production-B...
Baseline containing all updates approved for production systems pb-0a2f1059b670ebd31                                                  Production-B...
```
**範例 2：此範例列出 提供的所有修補程式基準 AWS。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
$filter1 = @{Key="OWNER";Values=@("AWS")}
```
**輸出：**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**範例 3：此範例列出了您作為擁有者的所有修補基準。此範例使用的語法需要 PowerShell 版本 3 或更新版本。**  

```
$filter1 = @{Key="OWNER";Values=@("Self")}
```
**輸出：**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**範例 4：使用 PowerShell 版本 2 時，必須使用 New-Object 來建立每個標籤。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "OWNER"
$filter1.Values = "AWS"

Get-SSMPatchBaseline -Filter $filter1
```
**輸出：**  

```
BaselineDescription                     BaselineId                                                            BaselineName             DefaultBaselin
                                                                                                                                       e
-------------------                     ----------                                                            ------------             --------------
Default Patch Baseline Provided by AWS. arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultPatchBaseline True
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribePatchBaselines](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMPatchBaselineDetail`
<a name="ssm_GetPatchBaseline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMPatchBaselineDetail`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示修補基準的詳細資訊。**  

```
Get-SSMPatchBaselineDetail -BaselineId "pb-03da896ca3b68b639"
```
**輸出：**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:02:19 PM
Name            : Production-Baseline
PatchGroups     : {}
RejectedPatches : {}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMPatchBaselineForPatchGroup`
<a name="ssm_GetPatchBaselineForPatchGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMPatchBaselineForPatchGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例顯示修補程式群組的修補基準。**  

```
Get-SSMPatchBaselineForPatchGroup -PatchGroup "Production"
```
**輸出：**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMPatchGroup`
<a name="ssm_DescribePatchGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMPatchGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了修補程式群組註冊。**  

```
Get-SSMPatchGroup
```
**輸出：**  

```
BaselineIdentity                                           PatchGroup
----------------                                           ----------
Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribePatchGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMPatchGroupState`
<a name="ssm_DescribePatchGroupState_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMPatchGroupState`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得修補程式群組的高階修補程式合規摘要。**  

```
Get-SSMPatchGroupState -PatchGroup "Production"
```
**輸出：**  

```
Instances                          : 4
InstancesWithFailedPatches         : 1
InstancesWithInstalledOtherPatches : 4
InstancesWithInstalledPatches      : 3
InstancesWithMissingPatches        : 0
InstancesWithNotApplicablePatches  : 0
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribePatchGroupState](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMResourceComplianceSummaryList`
<a name="ssm_ListResourceComplianceSummaries_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMResourceComplianceSummaryList`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取得資源層級摘要計數。摘要包含有關合規和不合規狀態的資訊，以及符合 "Windows10" 之產品的詳細合規項目嚴重性計數。由於未不指定該參數時，MaxResult 預設為 100，且該值無效，因此新增 MaxResult 參數，並將該值設定為 50。**  

```
$FilterValues = @{
		"Key"="Product"
        "Type"="EQUAL"
        "Values"="Windows10"
}
        Get-SSMResourceComplianceSummaryList -Filter $FilterValues -MaxResult 50
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListResourceComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMResourceTag`
<a name="ssm_ListTagsForResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-SSMResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例列出了維護時段的標籤。**  

```
Get-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow"
```
**輸出：**  

```
Key   Value
---   -----
Stack Production
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-SSMActivation`
<a name="ssm_CreateActivation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-SSMActivation`。

**Tools for PowerShell V5**  
**範例 1：此範例示範建立受管執行個體。**  

```
New-SSMActivation -DefaultInstanceName "MyWebServers" -IamRole "SSMAutomationRole" -RegistrationLimit 10
```
**輸出：**  

```
ActivationCode       ActivationId
--------------       ------------
KWChhOxBTiwDcKE9BlKC 08e51e79-1e36-446c-8e63-9458569c1363
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateActivation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-SSMAssociation`
<a name="ssm_CreateAssociation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-SSMAssociation`。

**Tools for PowerShell V5**  
**範例 1：此範例使用執行個體 ID 來關聯組態文件與執行個體。**  

```
New-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
**輸出：**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Associated
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : Associated with AWS-UpdateSSMAgent
Status.AdditionalInfo :
```
**範例 2：此範例使用目標來關聯組態文件與執行個體。**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
New-SSMAssociation -Name "AWS-UpdateSSMAgent" -Target $target
```
**輸出：**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**範例 3：此範例使用目標和參數來關聯組態文件與執行個體。**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
$params = @{
  "action"="configure"
  "mode"="ec2"
  "optionalConfigurationSource"="ssm"
  "optionalConfigurationLocation"=""
  "optionalRestart"="yes"
}
New-SSMAssociation -Name "Configure-CloudWatch" -AssociationName "CWConfiguration" -Target $target -Parameter $params
```
**輸出：**  

```
Name                  : Configure-CloudWatch
InstanceId            :
Date                  : 5/17/2018 3:17:44 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**範例 4：此範例使用 `AWS-GatherSoftwareInventory` 建立與區域中所有執行個體的關聯。它也提供參數中要收集的自訂檔案和登錄檔位置**  

```
$params = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$params["windowsRegistry"] ='[{"Path":"HKEY_LOCAL_MACHINE\SOFTWARE\Amazon\MachineImage","Recursive":false,"ValueNames":["AMIName"]}]'
$params["files"] = '[{"Path":"C:\Program Files","Pattern":["*.exe"],"Recursive":true}, {"Path":"C:\ProgramData","Pattern":["*.log"],"Recursive":true}]' 
New-SSMAssociation -AssociationName new-in-mum -Name AWS-GatherSoftwareInventory -Target @{Key="instanceids";Values="*"} -Parameter $params -region ap-south-1 -ScheduleExpression "rate(720 minutes)"
```
**輸出：**  

```
Name                  : AWS-GatherSoftwareInventory
InstanceId            :
Date                  : 6/9/2019 8:57:56 AM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-SSMAssociationFromBatch`
<a name="ssm_CreateAssociationBatch_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-SSMAssociationFromBatch`。

**Tools for PowerShell V5**  
**範例 1：此範例示範將組態文件與多個執行個體關聯。輸出會傳回成功操作和失敗操作的清單 (如適用)。**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
New-SSMAssociationFromBatch -Entry $option1,$option2
```
**輸出：**  

```
Failed  Successful
------  ----------
{}      {Amazon.SimpleSystemsManagement.Model.FailedCreateAssociation, Amazon.SimpleSystemsManagement.Model.FailedCreateAsso...
```
**範例 2：此範例會顯示成功操作的完整詳細資訊。**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
(New-SSMAssociationFromBatch -Entry $option1,$option2).Successful
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateAssociationBatch](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-SSMDocument`
<a name="ssm_CreateDocument_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-SSMDocument`。

**Tools for PowerShell V5**  
**範例 1：此範例示範在您的帳戶中建立文件。文件必須為 JSON 格式。如需有關撰寫組態文件的詳細資訊，請參閱《SSM API 參考》中的組態文件。**  

```
New-SSMDocument -Content (Get-Content -Raw "c:\temp\RunShellScript.json") -Name "RunShellScript" -DocumentType "Command"
```
**輸出：**  

```
CreatedDate     : 3/1/2017 1:21:33 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Creating
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateDocument](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-SSMMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-SSMMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立一個具有指定名稱的新維護時段，該維護時段在每個星期二下午 4 點執行 4 小時並有一個 1 小時的截止，而且允許未關聯的目標。**  

```
New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 -AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)"
```
**輸出：**  

```
mw-03eb53e1ea7383998
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-SSMPatchBaseline`
<a name="ssm_CreatePatchBaseline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-SSMPatchBaseline`。

**Tools for PowerShell V5**  
**範例 1：此範例示範針對在生產環境中執行 Windows Server 2019 的受管執行個體建立修補基準，該修補基準在 Microsoft 發行修補程式七天後對修補程式進行核准。**  

```
$rule = New-Object Amazon.SimpleSystemsManagement.Model.PatchRule
$rule.ApproveAfterDays = 7

$ruleFilters = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilterGroup

$patchFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$patchFilter.Key="PRODUCT"
$patchFilter.Values="WindowsServer2019"

$severityFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$severityFilter.Key="MSRC_SEVERITY"
$severityFilter.Values.Add("Critical")
$severityFilter.Values.Add("Important")
$severityFilter.Values.Add("Moderate")

$classificationFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$classificationFilter.Key = "CLASSIFICATION"
$classificationFilter.Values.Add( "SecurityUpdates" )
$classificationFilter.Values.Add( "Updates" )
$classificationFilter.Values.Add( "UpdateRollups" )
$classificationFilter.Values.Add( "CriticalUpdates" )

$ruleFilters.PatchFilters.Add($severityFilter)
$ruleFilters.PatchFilters.Add($classificationFilter)
$ruleFilters.PatchFilters.Add($patchFilter)
$rule.PatchFilterGroup = $ruleFilters

New-SSMPatchBaseline -Name "Production-Baseline-Windows2019" -Description "Baseline containing all updates approved for production systems" -ApprovalRules_PatchRule $rule
```
**輸出：**  

```
pb-0z4z6221c4296b23z
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-SSMDefaultPatchBaseline`
<a name="ssm_RegisterDefaultPatchBaseline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-SSMDefaultPatchBaseline`。

**Tools for PowerShell V5**  
**範例 1：此範例示範將修補基準註冊為預設修補基準。**  

```
Register-SSMDefaultPatchBaseline -BaselineId "pb-03da896ca3b68b639"
```
**輸出：**  

```
pb-03da896ca3b68b639
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-SSMPatchBaselineForPatchGroup`
<a name="ssm_RegisterPatchBaselineForPatchGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-SSMPatchBaselineForPatchGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例示範註冊修補程式群組的修補基準。**  

```
Register-SSMPatchBaselineForPatchGroup -BaselineId "pb-03da896ca3b68b639" -PatchGroup "Production"
```
**輸出：**  

```
BaselineId           PatchGroup
----------           ----------
pb-03da896ca3b68b639 Production
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-SSMTargetWithMaintenanceWindow`
<a name="ssm_RegisterTargetWithMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-SSMTargetWithMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例示範向維護時段註冊執行個體。**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**輸出：**  

```
d8e47760-23ed-46a5-9f28-927337725398
```
**範例 2：此範例示範向維護時段註冊多個執行個體。**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862","i-0cb2b964d3e14fd9f")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**輸出：**  

```
6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
**範例 3：此範例示範使用 EC2 標籤向維護時段註冊執行個體。**  

```
$option1 = @{Key="tag:Environment";Values=@("Production")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Production Web Servers" -ResourceType "INSTANCE"
```
**輸出：**  

```
2994977e-aefb-4a71-beac-df620352f184
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterTargetWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-SSMTaskWithMaintenanceWindow`
<a name="ssm_RegisterTaskWithMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-SSMTaskWithMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例示範使用執行個體 ID 向維護時段註冊任務。輸出為任務 ID。**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

Register-SSMTaskWithMaintenanceWindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="InstanceIds";Values="i-0000293ffd8c57862" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**輸出：**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**範例 2：此範例示範使用目標 ID 向維護時段註冊任務。輸出為任務 ID。**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

register-ssmtaskwithmaintenancewindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="WindowTargetIds";Values="350d44e6-28cc-44e2-951f-4b2c985838f6" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**輸出：**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**範例 3：此範例示範建立 Run Command 文件 `AWS-RunPowerShellScript` 的參數物件，並使用目標 ID 向指定維護時段建立任務。傳回輸出為任務 ID。**  

```
$parameters = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$parameters.Add("commands",@("ipconfig","dir env:\computername"))
$parameters.Add("executionTimeout",@(3600))

$props = @{
    WindowId = "mw-0123e4cce56ff78ae"
    ServiceRoleArn = "arn:aws:iam::123456789012:role/MaintenanceWindowsRole"
    MaxConcurrency = 1
    MaxError = 1
    TaskType = "RUN_COMMAND"
    TaskArn = "AWS-RunPowerShellScript"
    Target = @{Key="WindowTargetIds";Values="fe1234ea-56d7-890b-12f3-456b789bee0f"}
    Priority = 1
    RunCommand_Parameter = $parameters
    Name = "set-via-cmdlet"
}

Register-SSMTaskWithMaintenanceWindow @props
```
**輸出：**  

```
f1e2ef34-5678-12e3-456a-12334c5c6cbe
```
**範例 4：此範例會使用名為 的文件來註冊 AWS Systems Manager Automation 任務`Create-Snapshots`。**  

```
$automationParameters = @{}
$automationParameters.Add( "instanceId", @("{{ TARGET_ID }}") )
$automationParameters.Add( "AutomationAssumeRole", @("{arn:aws:iam::111111111111:role/AutomationRole}") )
$automationParameters.Add( "SnapshotTimeout", @("PT20M") )
Register-SSMTaskWithMaintenanceWindow -WindowId mw-123EXAMPLE456`
    -ServiceRoleArn "arn:aws:iam::123456789012:role/MW-Role"`
    -MaxConcurrency 1 -MaxError 1 -TaskArn "CreateVolumeSnapshots"`
    -Target @{ Key="WindowTargetIds";Values="4b5acdf4-946c-4355-bd68-4329a43a5fd1" }`
    -TaskType "AUTOMATION"`
    -Priority 4`
    -Automation_DocumentVersion '$DEFAULT' -Automation_Parameter $automationParameters -Name "Create-Snapshots"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterTaskWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SSMActivation`
<a name="ssm_DeleteActivation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SSMActivation`。

**Tools for PowerShell V5**  
**範例 1：此範例示範刪除啟用。如果命令成功，則無輸出訊息。**  

```
Remove-SSMActivation -ActivationId "08e51e79-1e36-446c-8e63-9458569c1363"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteActivation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SSMAssociation`
<a name="ssm_DeleteAssociation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SSMAssociation`。

**Tools for PowerShell V5**  
**範例 1：此範例示範刪除執行個體與文件之間的關聯。如果命令成功，則無輸出訊息。**  

```
Remove-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteAssociation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SSMDocument`
<a name="ssm_DeleteDocument_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SSMDocument`。

**Tools for PowerShell V5**  
**範例 1：此範例示範刪除文件。如果命令成功，則無輸出訊息。**  

```
Remove-SSMDocument -Name "RunShellScript"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteDocument](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SSMMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SSMMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例示範移除維護時段。**  

```
Remove-SSMMaintenanceWindow -WindowId "mw-06d59c1a07c022145"
```
**輸出：**  

```
mw-06d59c1a07c022145
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SSMParameter`
<a name="ssm_DeleteParameter_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SSMParameter`。

**Tools for PowerShell V5**  
**範例 1：此範例示範刪除參數。如果命令成功，則無輸出訊息。**  

```
Remove-SSMParameter -Name "helloWorld"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteParameter](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SSMPatchBaseline`
<a name="ssm_DeletePatchBaseline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SSMPatchBaseline`。

**Tools for PowerShell V5**  
**範例 1：此範例示範刪除修補基準。**  

```
Remove-SSMPatchBaseline -BaselineId "pb-045f10b4f382baeda"
```
**輸出：**  

```
pb-045f10b4f382baeda
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeletePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-SSMResourceTag`
<a name="ssm_RemoveTagsFromResource_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-SSMResourceTag`。

**Tools for PowerShell V5**  
**範例 1：此範例示範從維護時段中移除標籤。如果命令成功，則無輸出訊息。**  

```
Remove-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -TagKey "Production"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Send-SSMCommand`
<a name="ssm_SendCommand_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Send-SSMCommand`。

**Tools for PowerShell V5**  
**範例 1：此範例示範在目標執行個體上執行 echo 命令。**  

```
Send-SSMCommand -DocumentName "AWS-RunPowerShellScript" -Parameter @{commands = "echo helloWorld"} -Target @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
```
**輸出：**  

```
CommandId          : d8d190fc-32c1-4d65-a0df-ff5ff3965524
Comment            : 
CompletedCount     : 0
DocumentName       : AWS-RunPowerShellScript
ErrorCount         : 0
ExpiresAfter       : 3/7/2017 10:48:37 PM
InstanceIds        : {}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName : 
OutputS3KeyPrefix  : 
OutputS3Region     : 
Parameters         : {[commands, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 3/7/2017 9:48:37 PM
ServiceRole        : 
Status             : Pending
StatusDetails      : Pending
TargetCount        : 0
Targets            : {instanceids}
```
**範例 2：此範例顯示如何執行接受巢狀參數的命令。**  

```
Send-SSMCommand -DocumentName "AWS-RunRemoteScript" -Parameter @{ sourceType="GitHub";sourceInfo='{"owner": "me","repository": "amazon-ssm","path": "Examples/Install-Win32OpenSSH"}'; "commandLine"=".\Install-Win32OpenSSH.ps1"} -InstanceId i-0cb2b964d3e14fd9f
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [SendCommand](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-SSMAutomationExecution`
<a name="ssm_StartAutomationExecution_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-SSMAutomationExecution`。

**Tools for PowerShell V5**  
**範例 1：此範例示範執行指定自動化角色、AMI 來源 ID 和 Amazon EC2 執行個體角色的文件。**  

```
Start-SSMAutomationExecution -DocumentName AWS-UpdateLinuxAmi -Parameter @{'AutomationAssumeRole'='arn:aws:iam::123456789012:role/SSMAutomationRole';'SourceAmiId'='ami-f173cc91';'InstanceIamRole'='EC2InstanceRole'}
```
**輸出：**  

```
3a532a4f-0382-11e7-9df7-6f11185f6dd1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Start-SSMSession`
<a name="ssm_StartSession_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Start-SSMSession`。

**Tools for PowerShell V5**  
**範例 1：此範例示範啟動與 Session Manager 工作階段目標的連線，以啟用連接埠轉送。注意：如果尚未使用 AWSCredentials 設定區域參數，則需要新增區域參數。**  

```
Start-SSMSession -Target 'i-064578e5e7454488f' -DocumentName 'AWS-StartPortForwardingSession' -Parameter @{ localPortNumber = '8080'; portNumber = '80' } -Region 'us-west-1'
```
**輸出：**  

```
Starting session with SessionId: testUser-xi4glew849asyeryde34u4dfsdfy
Port 8080 opened for sessionId testUser-xi4glew849asyeryde34u4dfsdfy.
Waiting for connections...
```
**範例 2：此範例為 Session Manager 工作階段，與指定執行個體建立互動式工作階段。**  

```
Start-SSMSession -Target 'i-1234567890abcdef0' -Region 'us-west-1'
```
**輸出：**  

```
Starting session with SessionId : testUser-xi4glew849asyeryde34u4dfsdfy
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
                                                                                                                                                                                                
Install the latest PowerShell for new features and improvements!
                                                                                                                                                      
PS C:\Windows\system32> whoami
ec2amaz-fnsdrwv\ec2-test-user
PS C:\Windows\system32>
```
**範例 3：此範例會在不連線的情況下建立工作階段，並傳回連線至工作階段所需的 SessionId、StreamUrl 和 TokenValue 屬性。**  

```
Start-SSMSession -Target 'i-1234567890abcdef0' -Region 'us-west-1' -DisablePluginInvocation
```
**輸出：**  

```
SessionId        : testUser-xi4glew849asyeryde34u4dfsdfy
StreamUrl        : {StreamUrl value redacted}
TokenValue       : {Token value redacted}
ContentLength    : 1207
HttpStatusCode   : OK
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartSession](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-SSMAutomationExecution`
<a name="ssm_StopAutomationExecution_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-SSMAutomationExecution`。

**Tools for PowerShell V5**  
**範例 1：此範例示範停止自動化執行。如果命令成功，則無輸出訊息。**  

```
Stop-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-SSMCommand`
<a name="ssm_CancelCommand_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-SSMCommand`。

**Tools for PowerShell V5**  
**範例 1：此範例嘗試取消命令。如果操作成功，則無輸出訊息。**  

```
Stop-SSMCommand -CommandId "9ded293e-e792-4440-8e3e-7b8ec5feaa38"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelCommand](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-SSMManagedInstance`
<a name="ssm_DeregisterManagedInstance_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-SSMManagedInstance`。

**Tools for PowerShell V5**  
**範例 1：此範例示範取消註冊受管執行個體。如果命令成功，則無輸出訊息。**  

```
Unregister-SSMManagedInstance -InstanceId "mi-08ab247cdf1046573"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterManagedInstance](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-SSMPatchBaselineForPatchGroup`
<a name="ssm_DeregisterPatchBaselineForPatchGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-SSMPatchBaselineForPatchGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例示範從修補基準中取消註冊修補程式群組。**  

```
Unregister-SSMPatchBaselineForPatchGroup -BaselineId "pb-045f10b4f382baeda" -PatchGroup "Production"
```
**輸出：**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-SSMTargetFromMaintenanceWindow`
<a name="ssm_DeregisterTargetFromMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-SSMTargetFromMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例示範從維護時段中移除目標。**  

```
Unregister-SSMTargetFromMaintenanceWindow -WindowTargetId "6ab5c208-9fc4-4697-84b7-b02a6cc25f7d" -WindowId "mw-06cf17cbefcb4bf4f"
```
**輸出：**  

```
WindowId             WindowTargetId
--------             --------------
mw-06cf17cbefcb4bf4f 6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-SSMTaskFromMaintenanceWindow`
<a name="ssm_DeregisterTaskFromMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-SSMTaskFromMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例示範從維護時段中移除任務。**  

```
Unregister-SSMTaskFromMaintenanceWindow -WindowTaskId "f34a2c47-ddfd-4c85-a88d-72366b69af1b" -WindowId "mw-03a342e62c96d31b0"
```
**輸出：**  

```
WindowId             WindowTaskId
--------             ------------
mw-03a342e62c96d31b0 f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeregisterTaskFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-SSMAssociation`
<a name="ssm_UpdateAssociation_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-SSMAssociation`。

**Tools for PowerShell V5**  
**範例 1：此範例示範以新文件版本更新關聯。**  

```
Update-SSMAssociation -AssociationId "93285663-92df-44cb-9f26-2292d4ecc439" -DocumentVersion "1"
```
**輸出：**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-SSMAssociationStatus`
<a name="ssm_UpdateAssociationStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-SSMAssociationStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例示範更新執行個體與組態文件之間的關聯狀態。**  

```
Update-SSMAssociationStatus -Name "AWS-UpdateSSMAgent" -InstanceId "i-0000293ffd8c57862" -AssociationStatus_Date "2015-02-20T08:31:11Z" -AssociationStatus_Name "Pending" -AssociationStatus_Message "temporary_status_change" -AssociationStatus_AdditionalInfo "Additional-Config-Needed"
```
**輸出：**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temporary_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateAssociationStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-SSMDocument`
<a name="ssm_UpdateDocument_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-SSMDocument`。

**Tools for PowerShell V5**  
**範例 1：此範例示範建立新版本的文件，其中包含您指定的 json 檔案的更新內容。文件必須為 JSON 格式。您可以使用 "Get-SSMDocumentVersionList" cmdlet 取得文件版本。**  

```
Update-SSMDocument -Name RunShellScript -DocumentVersion "1" -Content (Get-Content -Raw "c:\temp\RunShellScript.json")
```
**輸出：**  

```
CreatedDate     : 3/1/2017 2:59:17 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 2
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 2
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Updating
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateDocument](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-SSMDocumentDefaultVersion`
<a name="ssm_UpdateDocumentDefaultVersion_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-SSMDocumentDefaultVersion`。

**Tools for PowerShell V5**  
**範例 1：此範例示範更新文件的預設版本。您可以使用 "Get-SSMDocumentVersionList" cmdlet 取得可用的文件版本。**  

```
Update-SSMDocumentDefaultVersion -Name "RunShellScript" -DocumentVersion "2"
```
**輸出：**  

```
DefaultVersion Name
-------------- ----
2              RunShellScript
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateDocumentDefaultVersion](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-SSMMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-SSMMaintenanceWindow`。

**Tools for PowerShell V5**  
**範例 1：此範例示範更新維護時段的名稱。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Name "My-Renamed-MW"
```
**輸出：**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**範例 2：此範例示範啟用維護時段。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $true
```
**輸出：**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**範例 3：此範例示範停用維護時段。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $false
```
**輸出：**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : False
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-SSMManagedInstanceRole`
<a name="ssm_UpdateManagedInstanceRole_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-SSMManagedInstanceRole`。

**Tools for PowerShell V5**  
**範例 1：此範例示範更新受管執行個體的角色。如果命令成功，則無輸出訊息。**  

```
Update-SSMManagedInstanceRole -InstanceId "mi-08ab247cdf1046573" -IamRole "AutomationRole"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateManagedInstanceRole](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-SSMPatchBaseline`
<a name="ssm_UpdatePatchBaseline_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Update-SSMPatchBaseline`。

**Tools for PowerShell V5**  
**範例 1：此範例示範將修補程式新增到現有修補基準，兩個修補程式新增為已拒絕，一個修補程式新增為已核准。**  

```
Update-SSMPatchBaseline -BaselineId "pb-03da896ca3b68b639" -RejectedPatch "KB2032276","MS10-048" -ApprovedPatch "KB2124261"
```
**輸出：**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {KB2124261}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:22:10 PM
Name            : Production-Baseline
RejectedPatches : {KB2032276, MS10-048}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-SSMComplianceItem`
<a name="ssm_PutComplianceItems_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-SSMComplianceItem`。

**Tools for PowerShell V5**  
**範例 1：此範例為指定的受管執行個體撰寫自訂合規項目**  

```
$item = [Amazon.SimpleSystemsManagement.Model.ComplianceItemEntry]::new()
$item.Id = "07Jun2019-3"
$item.Severity="LOW"
$item.Status="COMPLIANT"
$item.Title="Fin-test-1 - custom"
Write-SSMComplianceItem -ResourceId mi-012dcb3ecea45b678 -ComplianceType Custom:VSSCompliant2 -ResourceType ManagedInstance -Item $item -ExecutionSummary_ExecutionTime "07-Jun-2019"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-SSMInventory`
<a name="ssm_PutInventory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-SSMInventory`。

**Tools for PowerShell V5**  
**範例 1：此範例示範將機架位置資訊指派給執行個體。如果命令成功，則無輸出訊息。**  

```
$data = New-Object "System.Collections.Generic.Dictionary[System.String,System.String]"
$data.Add("RackLocation", "Bay B/Row C/Rack D/Shelf F")

$items = New-Object "System.Collections.Generic.List[System.Collections.Generic.Dictionary[System.String, System.String]]"
$items.Add($data)

$customInventoryItem = New-Object Amazon.SimpleSystemsManagement.Model.InventoryItem
$customInventoryItem.CaptureTime = "2016-08-22T10:01:01Z"
$customInventoryItem.Content = $items
$customInventoryItem.TypeName = "Custom:TestRackInfo2"
$customInventoryItem.SchemaVersion = "1.0"

$inventoryItems = @($customInventoryItem)

Write-SSMInventory -InstanceId "i-0cb2b964d3e14fd9f" -Item $inventoryItems
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutInventory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Write-SSMParameter`
<a name="ssm_PutParameter_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Write-SSMParameter`。

**Tools for PowerShell V5**  
**範例 1：此範例示範建立參數。如果命令成功，則無輸出訊息。**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "helloWorld"
```
**範例 2：此範例示範變更參數。如果命令成功，則無輸出訊息。**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "Good day, Sunshine!" -Overwrite $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutParameter](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 Amazon Translate 範例
<a name="powershell_translate_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 Amazon Translate 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `ConvertTo-TRNTargetLanguage`
<a name="translate_TranslateText_powershell_topic"></a>

以下程式碼範例顯示如何使用 `ConvertTo-TRNTargetLanguage`。

**Tools for PowerShell V5**  
**範例 1：將指定的英文文字轉換為法文。要轉換的文字也可以當作 -Text 參數來傳遞。**  

```
"Hello World" | ConvertTo-TRNTargetLanguage -SourceLanguageCode en -TargetLanguageCode fr
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TranslateText](https://docs.aws.amazon.com/powershell/v5/reference)。

# AWS WAFV2 使用 Tools for PowerShell V5 的範例
<a name="powershell_wafv2_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 來執行動作和實作常見案例 AWS WAFV2。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `New-WAF2WebACL`
<a name="wafv2_CreateWebAcl_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-WAF2WebACL`。

**Tools for PowerShell V5**  
**範例 1：此命令會建立名為 "waf-test" 的新 Web ACL。請注意，根據服務 API 文件，'DefaultAction' 是必要的屬性。因此，應該指定 '-DefaultAction\$1Allow' 和/或 '-DefaultAction\$1Block' 的值。由於 '-DefaultAction\$1Allow' 和 '-DefaultAction\$1Block' 不是必要的屬性，因此值 '@\$1\$1' 可以用作預留位置，如上述範例所示。**  

```
New-WAF2WebACL -Name "waf-test" -Scope REGIONAL -Region eu-west-1 -VisibilityConfig_CloudWatchMetricsEnabled $true -VisibilityConfig_SampledRequestsEnabled $true -VisibilityConfig_MetricName "waf-test" -Description "Test" -DefaultAction_Allow @{}
```
**輸出：**  

```
ARN         : arn:aws:wafv2:eu-west-1:139480602983:regional/webacl/waf-test/19460b3f-db14-4b9a-8e23-a417e1eb007f
Description : Test
Id          : 19460b3f-db14-4b9a-8e23-a417e1eb007f
LockToken   : 5a0cd5eb-d911-4341-b313-b429e6d6b6ab
Name        : waf-test
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateWebAcl](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用 Tools for PowerShell V5 的 WorkSpaces 範例
<a name="powershell_workspaces_code_examples"></a>

下列程式碼範例示範如何使用 AWS Tools for PowerShell V5 搭配 WorkSpaces 來執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `Approve-WKSIpRule`
<a name="workspaces_AuthorizeIpRules_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Approve-WKSIpRule`。

**Tools for PowerShell V5**  
**範例 1：此範例會將規則新增至現有的 IP 群組**  

```
$Rule = @(
@{IPRule = "10.1.0.0/0"; RuleDesc = "First Rule Added"},
@{IPRule = "10.2.0.0/0"; RuleDesc = "Second Rule Added"}
)

Approve-WKSIpRule -GroupId wsipg-abcnx2fcw -UserRule $Rule
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AuthorizeIpRules](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Copy-WKSWorkspaceImage`
<a name="workspaces_CopyWorkspaceImage_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Copy-WKSWorkspaceImage`。

**Tools for PowerShell V5**  
**範例 1：此範例會將具有指定 ID 的工作區映像，從 us-west-2 複製到名為 "CopiedImageTest" 的目前區域**  

```
Copy-WKSWorkspaceImage -Name CopiedImageTest -SourceRegion us-west-2 -SourceImageId wsi-djfoedhw6
```
**輸出：**  

```
wsi-456abaqfe
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CopyWorkspaceImage](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-WKSClientProperty`
<a name="workspaces_ModifyClientProperties_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-WKSClientProperty`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用 Workspaces 用戶端的重新連線**  

```
Edit-WKSClientProperty -Region us-west-2 -ClientProperties_ReconnectEnabled "ENABLED" -ResourceId d-123414a369
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyClientProperties](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-WKSSelfServicePermission`
<a name="workspaces_ModifySelfservicePermissions_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-WKSSelfServicePermission`。

**Tools for PowerShell V5**  
**範例 1：此範例會啟用自助服務權限來變更指定目錄的運算類型，並增加磁碟區大小**  

```
Edit-WKSSelfservicePermission -Region us-west-2 -ResourceId d-123454a369 -SelfservicePermissions_ChangeComputeType ENABLED -SelfservicePermissions_IncreaseVolumeSize ENABLED
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifySelfservicePermissions](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-WKSWorkspaceAccessProperty`
<a name="workspaces_ModifyWorkspaceAccessProperties_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-WKSWorkspaceAccessProperty`。

**Tools for PowerShell V5**  
**範例 1：此範例可為指定的目錄啟用 Android 和 Chrome 作業系統上的 Workspace 存取**  

```
Edit-WKSWorkspaceAccessProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceAccessProperties_DeviceTypeAndroid ALLOW -WorkspaceAccessProperties_DeviceTypeChromeOs ALLOW
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyWorkspaceAccessProperties](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-WKSWorkspaceCreationProperty`
<a name="workspaces_ModifyWorkspaceCreationProperties_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-WKSWorkspaceCreationProperty`。

**Tools for PowerShell V5**  
**範例 1：此範例在建立 Workspace 時，將網際網路存取和維護模式設為預設值**  

```
Edit-WKSWorkspaceCreationProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceCreationProperties_EnableInternetAccess $true -WorkspaceCreationProperties_EnableMaintenanceMode $true
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyWorkspaceCreationProperties](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-WKSWorkspaceProperty`
<a name="workspaces_ModifyWorkspaceProperties_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-WKSWorkspaceProperty`。

**Tools for PowerShell V5**  
**範例 1：此範例會將指定 Workspace 的 Workspace 執行模式屬性變更為自動停止**  

```
Edit-WKSWorkspaceProperty -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceProperties_RunningMode AUTO_STOP
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyWorkspaceProperties](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Edit-WKSWorkspaceState`
<a name="workspaces_ModifyWorkspaceState_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Edit-WKSWorkspaceState`。

**Tools for PowerShell V5**  
**範例 1：此範例將指定的 Workspace 狀態變更為可用**  

```
Edit-WKSWorkspaceState -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceState AVAILABLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ModifyWorkspaceState](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSClientProperty`
<a name="workspaces_DescribeClientProperties_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSClientProperty`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定目錄之 Workspace 用戶端的用戶端屬性**  

```
Get-WKSClientProperty -ResourceId d-223562a123
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeClientProperties](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSIpGroup`
<a name="workspaces_DescribeIpGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSIpGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會取得指定之區域中指定 IP 群組的詳細資訊**  

```
Get-WKSIpGroup -Region us-east-1 -GroupId wsipg-8m1234v45
```
**輸出：**  

```
GroupDesc GroupId         GroupName UserRules
--------- -------         --------- ---------
          wsipg-8m1234v45 TestGroup {Amazon.WorkSpaces.Model.IpRuleItem, Amazon.WorkSpaces.Model.IpRuleItem}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSTag`
<a name="workspaces_DescribeTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取給定 Workspace 的標籤**  

```
Get-WKSTag -WorkspaceId ws-w361s234r -Region us-west-2
```
**輸出：**  

```
Key         Value
---         -----
auto-delete no
purpose     Workbench
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSWorkspace`
<a name="workspaces_DescribeWorkspaces_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSWorkspace`。

**Tools for PowerShell V5**  
**範例 1：擷取管道中所有 WorkSpaces 的詳細資訊。**  

```
Get-WKSWorkspace
```
**輸出：**  

```
BundleId                    : wsb-1a2b3c4d
ComputerName                :
DirectoryId                 : d-1a2b3c4d
ErrorCode                   :
ErrorMessage                :
IpAddress                   :
RootVolumeEncryptionEnabled : False
State                       : PENDING
SubnetId                    :
UserName                    : myuser
UserVolumeEncryptionEnabled : False
VolumeEncryptionKey         :
WorkspaceId                 : ws-1a2b3c4d
WorkspaceProperties         : Amazon.WorkSpaces.Model.WorkspaceProperties
```
**範例 2：此命令顯示 `us-west-2` 區域中工作區的 `WorkSpaceProperties` 子屬性值。如需 `WorkSpaceProperties` 子屬性的詳細資訊，請參閱 https://docs.aws.amazon.com/workspaces/latest/api/API\$1WorkspaceProperties.html。**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties
```
**輸出：**  

```
        ComputeTypeName                     : STANDARD
        RootVolumeSizeGib                   : 80
        RunningMode                         : AUTO_STOP
        RunningModeAutoStopTimeoutInMinutes : 60
        UserVolumeSizeGib                   : 50
```
**範例 3：此命令顯示 `us-west-2` 區域中工作區的 `WorkSpaceProperties` 子屬性 `RootVolumeSizeGib` 的值。GiB 的根磁碟區大小為 80。**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties.RootVolumeSizeGib
```
**輸出：**  

```
        80
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSWorkspaceBundle`
<a name="workspaces_DescribeWorkspaceBundles_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSWorkspaceBundle`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取目前區域中所有 Workspace 搭售組合的詳細資訊**  

```
Get-WKSWorkspaceBundle
```
**輸出：**  

```
BundleId        : wsb-sfhdgv342
ComputeType     : Amazon.WorkSpaces.Model.ComputeType
Description     : This bundle is custom
ImageId         : wsi-235aeqges
LastUpdatedTime : 12/26/2019 06:44:07
Name            : CustomBundleTest
Owner           : 233816212345
RootStorage     : Amazon.WorkSpaces.Model.RootStorage
UserStorage     : Amazon.WorkSpaces.Model.UserStorage
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeWorkspaceBundles](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSWorkspaceDirectory`
<a name="workspaces_DescribeWorkspaceDirectories_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSWorkspaceDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例會列出已註冊目錄的目錄詳細資訊**  

```
Get-WKSWorkspaceDirectory
```
**輸出：**  

```
Alias                       : TestWorkspace
CustomerUserName            : Administrator
DirectoryId                 : d-123414a369
DirectoryName               : TestDirectory.com
DirectoryType               : MicrosoftAD
DnsIpAddresses              : {172.31.43.45, 172.31.2.97}
IamRoleId                   : arn:aws:iam::761234567801:role/workspaces_RoleDefault
IpGroupIds                  : {}
RegistrationCode            : WSpdx+4RRT43
SelfservicePermissions      : Amazon.WorkSpaces.Model.SelfservicePermissions
State                       : REGISTERED
SubnetIds                   : {subnet-1m3m7b43, subnet-ard11aba}
Tenancy                     : SHARED
WorkspaceAccessProperties   : Amazon.WorkSpaces.Model.WorkspaceAccessProperties
WorkspaceCreationProperties : Amazon.WorkSpaces.Model.DefaultWorkspaceCreationProperties
WorkspaceSecurityGroupId    : sg-0ed2441234a123c43
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeWorkspaceDirectories](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSWorkspaceImage`
<a name="workspaces_DescribeWorkspaceImages_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSWorkspaceImage`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取區域中所有影像的所有詳細資訊**  

```
Get-WKSWorkspaceImage
```
**輸出：**  

```
Description     :This image is copied from another image
ErrorCode       :
ErrorMessage    :
ImageId         : wsi-345ahdjgo
Name            : CopiedImageTest
OperatingSystem : Amazon.WorkSpaces.Model.OperatingSystem
RequiredTenancy : DEFAULT
State           : AVAILABLE
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeWorkspaceImages](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSWorkspaceSnapshot`
<a name="workspaces_DescribeWorkspaceSnapshots_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSWorkspaceSnapshot`。

**Tools for PowerShell V5**  
**範例 1：此範例示範針對指定之 Workspace 建立的最新快照時間戳記**  

```
Get-WKSWorkspaceSnapshot -WorkspaceId ws-w361s100v
```
**輸出：**  

```
RebuildSnapshots                   RestoreSnapshots
----------------                   ----------------
{Amazon.WorkSpaces.Model.Snapshot} {Amazon.WorkSpaces.Model.Snapshot}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeWorkspaceSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-WKSWorkspacesConnectionStatus`
<a name="workspaces_DescribeWorkspacesConnectionStatus_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Get-WKSWorkspacesConnectionStatus`。

**Tools for PowerShell V5**  
**範例 1：此範例會擷取指定之 Workspace 的連線狀態**  

```
Get-WKSWorkspacesConnectionStatus -WorkspaceId ws-w123s234r
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeWorkspacesConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-WKSIpGroup`
<a name="workspaces_CreateIpGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-WKSIpGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 FreshEmptyIpGroup 的空 Ip 群組**  

```
New-WKSIpGroup -GroupName "FreshNewIPGroup"
```
**輸出：**  

```
wsipg-w45rty4ty
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateIpGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-WKSTag`
<a name="workspaces_CreateTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-WKSTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會將新標籤新增至名為 `ws-wsname` 的工作區。標籤的索引鍵為 "Name"，索引鍵值為 `AWS_Workspace`。**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag
```
**範例 2：此範例會將多個標籤新增至名為 `ws-wsname` 的工作區。一個標籤的索引鍵為 "Name"，且索引鍵值為 `AWS_Workspace`；另一個標籤的標籤索引鍵為 "Stage"，且索引鍵值為 "Test"。**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"

$tag2 = New-Object Amazon.WorkSpaces.Model.Tag
$tag2.Key = "Stage"
$tag2.Value = "Test"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag,$tag2
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-WKSWorkspace`
<a name="workspaces_CreateWorkspaces_powershell_topic"></a>

以下程式碼範例顯示如何使用 `New-WKSWorkspace`。

**Tools for PowerShell V5**  
**範例 1：為提供的搭售組合、目錄和使用者建立 WorkSpace。**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME"}
```
**範例 2：此範例會建立多個 WorkSpaces**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_1"},@{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_2"}
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-WKSIpGroup`
<a name="workspaces_AssociateIpGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-WKSIpGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會向指定的目錄註冊指定的 IP 群組**  

```
Register-WKSIpGroup -GroupId wsipg-23ahsdres -DirectoryId d-123412e123
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [AssociateIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Register-WKSWorkspaceDirectory`
<a name="workspaces_RegisterWorkspaceDirectory_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Register-WKSWorkspaceDirectory`。

**Tools for PowerShell V5**  
**範例 1：此範例會為 Workspaces Service 註冊指定目錄**  

```
Register-WKSWorkspaceDirectory -DirectoryId d-123412a123 -EnableWorkDoc $false
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RegisterWorkspaceDirectory](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-WKSIpGroup`
<a name="workspaces_DeleteIpGroup_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-WKSIpGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會刪除指定的 IP 群組**  

```
Remove-WKSIpGroup -GroupId wsipg-32fhgtred
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSIpGroup (DeleteIpGroup)" on target "wsipg-32fhgtred".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteIpGroup](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-WKSTag`
<a name="workspaces_DeleteTags_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-WKSTag`。

**Tools for PowerShell V5**  
**範例 1：此範例會移除與 Workspace 相關聯的標籤**  

```
Remove-WKSTag -ResourceId ws-w10b3abcd -TagKey "Type"
```
**輸出：**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSTag (DeleteTags)" on target "ws-w10b3abcd".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-WKSWorkspace`
<a name="workspaces_TerminateWorkspaces_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Remove-WKSWorkspace`。

**Tools for PowerShell V5**  
**範例 1：終止多個 WorkSpaces。使用 -Force 切換變數可阻止 Cmdlet 提示確認。**  

```
Remove-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0" -Force
```
**範例 2：擷取所有 WorkSpaces 的集合，並將 ID 傳輸至 Remove-WKSWorkspace 的 -WorkSpaceId 參數，終止所有 WorkSpaces。Cmdlet 會在每個 WorkSpace 終止之前提示。若要隱藏確認提示，請新增 -Force 切換變數。**  

```
Get-WKSWorkspaces | Remove-WKSWorkspace
```
**範例 3：此範例示範如何傳遞定義要終止之 WorkSpaces 的 TerminateRequest 物件。除非也指定 -Force 切換變數，否則 Cmdlet 會提示確認。**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Remove-WKSWorkspace -Request $arrRequest
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [TerminateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Reset-WKSWorkspace`
<a name="workspaces_RebuildWorkspaces_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Reset-WKSWorkspace`。

**Tools for PowerShell V5**  
**範例 1：重建指定的 WorkSpace。**  

```
Reset-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**範例 2：擷取所有 WorkSpaces 的集合，並將 ID 傳輸至 Reset-WKSWorkspace 的 -WorkSpaceId 參數，導致 WorkSpaces 重建。**  

```
Get-WKSWorkspaces | Reset-WKSWorkspace
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RebuildWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Restart-WKSWorkspace`
<a name="workspaces_RebootWorkspaces_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Restart-WKSWorkspace`。

**Tools for PowerShell V5**  
**範例 1：重新啟動指定的 WorkSpace。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**範例 2：重新啟動多個 WorkSpaces。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d","ws-5a6b7c8d"
```
**範例 3：擷取所有 WorkSpaces 的集合，並將 ID 傳輸至 Restart-WKSWorkspace 的 -WorkSpaceId 參數，導致 WorkSpaces 重新啟動。**  

```
Get-WKSWorkspaces | Restart-WKSWorkspace
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [RebootWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Stop-WKSWorkspace`
<a name="workspaces_StopWorkspaces_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Stop-WKSWorkspace`。

**Tools for PowerShell V5**  
**範例 1：停止多個 WorkSpaces。**  

```
Stop-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0"
```
**範例 2：擷取所有 WorkSpaces 的集合，並將 ID 傳輸至 Stop-WKSWorkspace 的 -WorkSpaceId 參數，導致 WorkSpaces 停止。**  

```
Get-WKSWorkspaces | Stop-WKSWorkspace
```
**範例 3：此範例示範如何傳遞 StopRequest 物件，定義要停止的 WorkSpaces。**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Stop-WKSWorkspace -Request $arrRequest
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Unregister-WKSIpGroup`
<a name="workspaces_DisassociateIpGroups_powershell_topic"></a>

以下程式碼範例顯示如何使用 `Unregister-WKSIpGroup`。

**Tools for PowerShell V5**  
**範例 1：此範例會從指定的目錄取消註冊指定的 IP 群組**  

```
Unregister-WKSIpGroup -GroupId wsipg-12abcdphq -DirectoryId d-123454b123
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DisassociateIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)。