

的版本 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使用。

*基本功能*是向您展示如何在服务中执行基本操作的代码示例。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

*场景*是向您展示如何通过在一个服务中调用多个函数或与其他 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 Identity](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)
+ [资源组标记 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)

# 使用 V5 工具的 ACM 示例 PowerShell
<a name="powershell_acm_code_examples"></a>

以下代码示例向您展示了如何使用带有 ACM 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `Get-ACMCertificate`。

**适用于 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 参考 (V* 5) [GetCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ACMCertificateDetail`。

**适用于 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 参考 (V* 5) [DescribeCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ACMCertificateList`。

**适用于 PowerShell V5 的工具**  
**示例 1：检索所有证书的列表 ARNs 以及每个证书的域名。cmdlet 将自动分页以检索所有。 ARNs要手动控制分页，请使用-MaxItem 参数控制每次服务调 ARNs 用返回的证书数量，使用-NextToken 参数表示每次调用的起点。**  

```
Get-ACMCertificateList
```
**输出**：  

```
CertificateArn                                                                      DomainName
--------------                                                                      ----------
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012 www.example.com
```
**示例 2：检索所有证书的列表， ARNs 其中证书状态与所提供的状态相匹配。**  

```
Get-ACMCertificateList -CertificateStatus "VALIDATION_TIMED_OUT","FAILED"
```
**示例 3：此示例返回 us-east-1 区域中密钥类型为 RSA\$12048 且扩展密钥用法或用途为 CODE\$1SIGNING 的所有证书的列表。您可以在过滤 ListCertificates 器 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 参考 (V* 5) [ListCertificates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-ACMCertificate`。

**适用于 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 参考 (V* 5) [RequestCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ACMCertificate`。

**适用于 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 参考 (V* 5) [DeleteCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Send-ACMValidationEmail`。

**适用于 PowerShell V5 的工具**  
**示例 1：请求发送用于验证“www.example.com”的域所有权的电子邮件。如果您的 shell ConfirmPreference 的 \$1 设置为 “中” 或更低，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 参考 (V* 5) [ResendValidationEmail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的应用程序 Auto Scaling 示例
<a name="powershell_application-auto-scaling_code_examples"></a>

以下代码示例向您展示了如何使用带有 Application Auto Scaling 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `Add-AASScalableTarget`。

**适用于 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 参考 (V* 5) [RegisterScalableTarget](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-AASScalableTarget`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将提供有关指定命名空间中 Application Auto Scaling 可扩展目标的信息。**  

```
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 参考 (V* 5) [DescribeScalableTargets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-AASScalingActivity`。

**适用于 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 参考 (V* 5) [DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-AASScalingPolicy`。

**适用于 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 参考 (V* 5) [DescribeScalingPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-AASScheduledAction`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 列出了为自动扩缩组计划但尚未运行的操作或尚未达到其结束时间的操作。**  

```
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 参考 (V* 5) [DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-AASScalableTarget`。

**适用于 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 参考 (V* 5) [DeregisterScalableTarget](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-AASScalingPolicy`。

**适用于 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 参考 (V* 5) [DeleteScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-AASScheduledAction`。

**适用于 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 参考 (V* 5) [DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Set-AASScalingPolicy`。

**适用于 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 参考 (V* 5) [PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Set-AASScheduledAction`。

**适用于 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 参考 (V* 5) [PutScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# WorkSpaces 使用适用于 PowerShell V5 的工具的应用示例
<a name="powershell_appstream_code_examples"></a>

以下代码示例向您展示了如何使用带 WorkSpaces 应用程序的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `Add-APSResourceTag`。

**适用于 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 参考 (V* 5) [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Copy-APSImage`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将映像复制到其它区域**  

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

```
TestImageCopy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CopyImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Disable-APSUSer`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁用 USERPOOL 中的用户**  

```
Disable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Enable-APSUser`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在 USERPOOL 中启用禁用的用户**  

```
Enable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSAssociatedFleetList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例显示与堆栈关联的实例集**  

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

```
PowershellFleet
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListAssociatedFleets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSAssociatedStackList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例显示与实例集关联的堆栈**  

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

```
PowershellStack
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListAssociatedStacks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSDirectoryConfigList`。

**适用于 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 参考 (V* 5) [DescribeDirectoryConfigs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSFleetList`。

**适用于 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 参考 (V* 5) [DescribeFleets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSImageBuilderList`。

**适用于 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 参考 (V* 5) [DescribeImageBuilders](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSImageList`。

**适用于 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 参考 (V* 5) [DescribeImages](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSImagePermission`。

**适用于 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 参考 (V* 5) [DescribeImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSSessionList`。

**适用于 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 参考 (V* 5) [DescribeSessions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSStackList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例显示 AppStream 堆栈列表**  

```
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 参考 (V* 5) [DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSTagsForResourceList`。

**适用于 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 参考 (V* 5) [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSUsageReportSubscription`。

**适用于 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 参考 (V* 5) [DescribeUsageReportSubscriptions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSUser`。

**适用于 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 参考 (V* 5) [DescribeUsers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-APSUserStackAssociation`。

**适用于 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 参考 (V* 5) [DescribeUserStackAssociations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-APSDirectoryConfig`。

**适用于 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 参考 (V* 5) [CreateDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-APSFleet`。

**适用于 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 参考 (V* 5) [CreateFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-APSImageBuilder`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在中创建了 Image Builder 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 参考 (V* 5) [CreateImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-APSImageBuilderStreamingURL`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建了一个有效期为 2 小时的 ImageBuilder 直播网址**  

```
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 参考 (V* 5) 中的[CreateImageBuilderStreaming网址](https://docs.aws.amazon.com/powershell/v5/reference)。

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

以下代码示例演示了如何使用 `New-APSStack`。

**适用于 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 参考 (V* 5) [CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-APSStreamingURL`。

**适用于 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 参考 (V* 5) 中的[CreateStreaming网址](https://docs.aws.amazon.com/powershell/v5/reference)。

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

以下代码示例演示了如何使用 `New-APSUsageReportSubscription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用 AppStream 使用情况报告**  

```
New-APSUsageReportSubscription
```
**输出**：  

```
S3BucketName                                   Schedule
------------                                   --------
appstream-logs-us-east-1-123456789012-sik2hnxe DAILY
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateUsageReportSubscription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-APSUser`。

**适用于 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 参考 (V* 5) [CreateUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Register-APSFleet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用堆栈注册实例集**  

```
Register-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AssociateFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Register-APSUserStackBatch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将堆栈分配给 USERPOOL 中的用户**  

```
Register-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [BatchAssociateUserStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSDirectoryConfig`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了 AppStream 目录配置**  

```
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 参考 (V* 5) [DeleteDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSFleet`。

**适用于 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 参考 (V* 5) [DeleteFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSImage`。

**适用于 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 参考 (V* 5) [DeleteImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSImageBuilder`。

**适用于 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 参考 (V* 5) [DeleteImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSImagePermission`。

**适用于 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 参考 (V* 5) [DeleteImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSResourceTag`。

**适用于 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 参考 (V* 5) [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSStack`。

**适用于 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 参考 (V* 5) [DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSUsageReportSubscription`。

**适用于 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 参考 (V* 5) [DeleteUsageReportSubscription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-APSUser`。

**适用于 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 参考 (V* 5) [DeleteUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Revoke-APSSession`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例撤消了与舰队的会话 AppStream **  

```
Revoke-APSSession -SessionId 6cd2f9a3-f948-4aa1-8014-8a7dcde14877
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ExpireSession](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Start-APSFleet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启动实例集**  

```
Start-APSFleet -Name PowershellFleet
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StartFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Start-APSImageBuilder`。

**适用于 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 参考 (V* 5) [StartImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Stop-APSFleet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例停止实例集**  

```
Stop-APSFleet -Name PowershellFleet
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StopFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Stop-APSImageBuilder`。

**适用于 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 参考 (V* 5) [StopImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Unregister-APSFleet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从堆栈中取消注册实例集**  

```
Unregister-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisassociateFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Unregister-APSUserStackBatch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将用户从分配的堆栈中移除**  

```
Unregister-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [BatchDisassociateUserStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-APSDirectoryConfig`。

**适用于 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 参考 (V* 5) [UpdateDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-APSFleet`。

**适用于 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 参考 (V* 5) [UpdateFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-APSImagePermission`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例与其他账户共享 AppStream 图片**  

```
Update-APSImagePermission -Name Powershell -SharedAccountId 123456789012 -ImagePermissions_AllowFleet $True -ImagePermissions_AllowImageBuilder $True
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-APSStack`。

**适用于 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 参考 (V* 5) [UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Aurora 示例
<a name="powershell_aurora_code_examples"></a>

以下代码示例向您展示了如何使用带有 Aurora 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `Get-RDSOrderableDBInstanceOption`。

**适用于 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 参考文档 (V* 5) 中的[DescribeOrderableDBInstance选项](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用适用于 PowerShell V5 的工具的 Auto Scaling 示例
<a name="powershell_auto-scaling_code_examples"></a>

以下代码示例向您展示了如何使用带有 Auto Scaling 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `Add-ASLoadBalancer`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的负载均衡器附加到指定的自动扩缩组。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Complete-ASLifecycleAction`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例完成了指定的生命周期操作。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Disable-ASMetricsCollection`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁用对指定自动扩缩组指定指标的监控。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**示例 2：此示例禁用对指定自动扩缩组所有指标的监控。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Dismount-ASInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的实例与指定的自动扩缩组分离，并减少所需容量以使 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 会启动一个替换实例。**  

```
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 参考 (V* 5) [DetachInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Dismount-ASLoadBalancer`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的负载均衡器与指定的自动扩缩组分离。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Enable-ASMetricsCollection`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用对指定自动扩缩组指定指标的监控。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**示例 2：此示例启用对指定自动扩缩组所有指标的监控。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Enter-ASStandby`。

**适用于 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 参考 (V* 5) [EnterStandby](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Exit-ASStandby`。

**适用于 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 参考 (V* 5) [ExitStandby](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASAccountLimit`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述了您的 AWS 账户的 Auto Scaling 资源限制。**  

```
Get-ASAccountLimit
```
**输出**：  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASAdjustmentType`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述 Auto Scaling 所支持的调整类型。**  

```
Get-ASAdjustmentType
```
**输出**：  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASAutoScalingGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出自动扩缩组的名称。**  

```
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：此示例描述指定的自动扩缩组。**  

```
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：此示例描述指定的两个自动扩缩组。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**示例 4：此示例描述指定自动扩缩组的 Auto Scaling 实例。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**示例 5：此示例描述所有自动扩缩组。**  

```
Get-ASAutoScalingGroup
```
**示例 6：此示例描述了指定 LaunchTemplate 的 Auto Scaling 组。此示例假设“实例购买选项”设置为“遵照启动模板”。如果此选项设置为 “合并购买选项和实例类型”，则 LaunchTemplate 可以使用 “进行访问MixedInstancesPolicy。 LaunchTemplate“财产。**  

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

```
LaunchTemplateId     LaunchTemplateName   Version
----------------     ------------------   -------
lt-06095fd619cb40371 test-launch-template $Default
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASAutoScalingInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出了您的 IDs Auto Scaling 实例。**  

```
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 实例。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**示例 5：此示例描述所有 Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASAutoScalingNotificationType`。

**适用于 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 参考 (V* 5) [DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASLaunchConfiguration`。

**适用于 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 参考 (V* 5) [DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASLifecycleHook`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定的生命周期挂钩。**  

```
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：此示例描述指定自动扩缩组的所有生命周期挂钩。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**示例 3：此示例描述所有自动扩缩组的所有生命周期挂钩。**  

```
Get-ASLifecycleHook
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASLifecycleHookType`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的生命周期挂钩类型。**  

```
Get-ASLifecycleHookType
```
**输出**：  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASLoadBalancer`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组的负载均衡器。**  

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

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASMetricCollectionType`。

**适用于 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 参考 (V* 5) [DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASNotificationConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述与指定自动扩缩组关联的通知操作。**  

```
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：此示例描述与所有自动扩缩组关联的通知操作。**  

```
Get-ASNotificationConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组的所有策略。**  

```
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：此示例描述指定自动扩缩组的指定策略。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**示例 3：此示例描述所有自动扩缩组的所有策略。**  

```
Get-ASPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribePolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASScalingActivity`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组过去六周的扩缩活动。**  

```
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：此示例描述所有自动扩缩组过去六周的扩缩活动。**  

```
Get-ASScalingActivity
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASScalingProcessType`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的进程类型。**  

```
Get-ASScalingProcessType
```
**输出**：  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASScheduledAction`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组的计划扩缩操作。**  

```
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：此示例描述所有自动扩缩组的计划扩缩操作。**  

```
Get-ASScheduledAction
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASTag`。

**适用于 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：此示例描述所有自动扩缩组的所有标签。**  

```
Get-ASTag
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-ASTerminationPolicyType`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的终止策略。**  

```
Get-ASTerminationPolicyType
```
**输出**：  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Mount-ASInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的实例附加到指定的自动扩缩组。Auto Scaling 会自动增加自动扩缩组的所需容量。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-ASAutoScalingGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用指定的名称和属性创建自动扩缩组。默认所需容量为最小大小。因此，此自动扩缩组启动两个实例，指定的两个可用区中各一个。**  

```
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 参考 (V* 5) [CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-ASLaunchConfiguration`。

**适用于 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 参考 (V* 5) [CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ASAutoScalingGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：如果指定的自动扩缩组没有正在运行的实例，则此示例将删除该组。在操作继续之前，系统会提示您进行确认。**  

```
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：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force
```
**示例 3：此示例删除指定的自动扩缩组并终止该组包含的所有正在运行的实例。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ASLaunchConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：如果指定的启动配置未附加到自动扩缩组，则此示例将删除该配置。在操作继续之前，系统会提示您进行确认。**  

```
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：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ASLifecycleHook`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定生命周期挂钩。在操作继续之前，系统会提示您进行确认。**  

```
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：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ASNotificationConfiguration`。

**适用于 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：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic" -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ASPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定策略。在操作继续之前，系统会提示您进行确认。**  

```
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：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ASScheduledAction`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定计划操作。在操作继续之前，系统会提示您进行确认。**  

```
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：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction" -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-ASTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从指定的自动扩缩组删除指定的标签。在操作继续之前，系统会提示您进行确认。此示例使用的语法需要 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：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
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 参考 (V* 5) [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Resume-ASProcess`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例恢复指定自动扩缩组的指定 Auto Scaling 进程。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**示例 2：此示例恢复指定自动扩缩组的所有暂停 Auto Scaling 进程。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResumeProcesses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Set-ASDesiredCapacity`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例设置指定自动扩缩组的大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**示例 2：此示例设置指定自动扩缩组的大小，并等待冷却时间结束后再扩缩到新大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Set-ASInstanceHealth`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定实例的状态设置为“运行状况不佳”，使其停止服务。Auto Scaling 会终止并替换该实例。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**示例 2：此示例将指定实例的状态设置为“运行状况正常”，使其保持服务状态。未遵守自动扩缩组的任何运行状况检查宽限期。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [SetInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Set-ASInstanceProtection`。

**适用于 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 参考 (V* 5) [SetInstanceProtection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Set-ASTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例向指定的自动扩缩组添加单个标签。标签键为 “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 = 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 参考 (V* 5) [CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Start-ASPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例对指定的自动扩缩组执行指定的策略。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**示例 2：此示例在等待冷却时间结束后，对指定的自动扩缩组执行指定的策略。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ExecutePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Stop-ASInstanceInAutoScalingGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例终止了指定的实例，并减少其自动扩缩组的所需容量，以使 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 会启动一个替换实例。**  

```
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 参考 (V* 5) [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Suspend-ASProcess`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例暂停了指定自动扩缩组的指定 Auto Scaling 进程。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**示例 2：此示例暂停了指定自动扩缩组的所有 Auto Scaling 进程。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [SuspendProcesses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-ASAutoScalingGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新指定自动扩缩组的最小和最大大小。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**示例 2：此示例更新指定自动扩缩组的默认冷却时间。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**示例 3：此示例更新指定自动扩缩组的可用区。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**示例 4：此示例更新指定的自动扩缩组以使用 Elastic Load Balancing 运行状况检查。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Write-ASLifecycleActionHeartbeat`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例记录指定生命周期操作的心跳。这会使实例保持待处理状态，直到您完成自定义操作。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Write-ASLifecycleHook`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的生命周期挂钩添加到指定的自动扩缩组。**  

```
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 参考 (V* 5) [PutLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Write-ASNotificationConfiguration`。

**适用于 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 参考 (V* 5) [PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Write-ASScalingPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的策略添加到指定的自动扩缩组。指定的调整类型决定了如何解释 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 参考 (V* 5) [PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Write-ASScheduledUpdateGroupAction`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建或更新一次性计划操作，以在指定的开始时间更改所需容量。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS Budgets 使用 PowerShell V5 工具的示例
<a name="powershell_budgets_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS Budgets的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `New-BGTBudget`。

**适用于 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 参考 (V* 5) [CreateBudget](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS Cloud9 使用 PowerShell V5 工具的示例
<a name="powershell_cloud9_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS Cloud9的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `Get-C9EnvironmentData`。

**适用于 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 参考 (V* 5) [DescribeEnvironments](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-C9EnvironmentList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取可用的 AWS Cloud9 开发环境标识符列表。**  

```
Get-C9EnvironmentList
```
**输出**：  

```
685f892f431b45c2b28cb69eadcdb0EX
1980b80e5f584920801c09086667f0EX
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListEnvironments](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-C9EnvironmentMembershipList`。

**适用于 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 参考 (V* 5) [DescribeEnvironmentMemberships](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-C9EnvironmentStatus`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定 AWS Cloud9 开发环境的状态信息。**  

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

```
Message                     Status
-------                     ------
Environment is ready to use ready
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeEnvironmentStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-C9EnvironmentEC2`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用指定设置创建一个 AWS Cloud9 开发环境，启动亚马逊弹性计算云 (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 参考 (V* 5) 中的 [CreateEnvironmentEc2](https://docs.aws.amazon.com/powershell/v5/reference)。

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

以下代码示例演示了如何使用 `New-C9EnvironmentMembership`。

**适用于 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 参考 (V* 5) [CreateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-C9Environment`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定的 AWS Cloud9 开发环境。如果 Amazon EC2 实例已连接到环境，也会终止该实例。**  

```
Remove-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteEnvironment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-C9EnvironmentMembership`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从指定的 AWS Cloud9 开发环境中删除指定的环境成员。**  

```
Remove-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-C9Environment`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更改了指定现有 AWS Cloud9 开发环境的指定设置。**  

```
Update-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Description "My changed demonstration development environment." -Name my-changed-demo-env
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateEnvironment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-C9EnvironmentMembership`。

**适用于 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 参考 (V* 5) [UpdateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# CloudFormation 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_cloudformation_code_examples"></a>

以下代码示例向您展示了如何使用带 CloudFormation的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

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

以下代码示例演示了如何使用 `Get-CFNStack`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回描述用户的所有堆栈的堆栈实例集合。**  

```
Get-CFNStack
```
**示例 2：返回描述指定堆栈的堆栈实例**  

```
Get-CFNStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-CFNStackEvent`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定堆栈的所有堆栈相关事件。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeStackEvents](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-CFNStackResource`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回模板中按逻辑 ID DBInstance “我的” 标识的与指定堆栈关联的资源的描述。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeStackResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-CFNStackResourceList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回与指定堆栈关联的多达 100 个资源的 AWS 资源描述。要获取与堆栈关联的所有资源的详细信息，请使用 Get-CFNStackResourceSummary，它还支持手动分页结果。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**示例 2：返回在模板中通过逻辑 ID “Ec2Instance” 标识的与指定堆栈关联的亚马逊 EC2 实例的描述。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**示例 3：返回与堆栈关联的多达 100 个资源的描述，该堆栈包含一个由 EC2 实例 ID “i-123456” 标识的 Amazon 实例。要获取与堆栈关联的所有资源的详细信息，请使用 Get-CFNStackResourceSummary，它还支持手动分页结果。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456"
```
**示例 4：返回由堆栈模板中的逻辑 ID “Ec2Instance” 标识的 Amazon EC2 实例的描述。堆栈使用其包含的资源的物理资源 ID 进行标识，在本例中也是 EC2 实例 ID 为 “i-123456” 的 Amazon 实例。也可以根据模板内容使用其他物理资源来识别堆栈，例如 Amazon S3 存储桶。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456" -LogicalResourceId "Ec2Instance"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeStackResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-CFNStackResourceSummary`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回与指定堆栈关联的所有资源的描述。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListStackResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-CFNStackSummary`。

**适用于 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 参考 (V* 5) [ListStacks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Get-CFNTemplate`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回与指定堆栈关联的模板。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetTemplate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Measure-CFNTemplateCost`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回一个带有查询字符串的 AWS 简单月度计算器网址，该字符串描述了运行模板所需的资源。模板是从指定的 Amazon S3 URL 获取的，并且应用了单个自定义参数。也可以使用 “键” 和 “值” 来指定参数，而不是 “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 简单月度结算器网址，该字符串描述了运行模板所需的资源。模板是根据提供的内容和应用的自定义参数进行解析的（此示例假设模板内容会声明两个参数，'和KeyName' InstanceType '）。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**示例 3：使用 New-Object 生成模板参数集，并返回一个 “ AWS 简单月度计算器” 网址，其中包含描述运行模板所需资源的查询字符串。模板是从提供的内容中解析出来的，并带有自定义参数（此示例假设模板内容会声明两个参数，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 参考 (V* 5) [EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `New-CFNStack`。

**适用于 PowerShell V5 的工具**  
**示例 1：使用指定名称创建新堆栈。模板是从提供的内容中解析出来的，带有自定义参数（PK1'PK2' 和 '' 代表模板内容中声明的参数的名称，PV1'和' PV2 '代表这些参数的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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 '代表这些参数的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用指定名称创建新堆栈。该模板是从带有自定义参数的 Amazon S3 URL 中获取的（PK1“” 表示模板内容中声明的参数的名称，PV1“” 表示参数的值。 也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用指定名称创建新堆栈。该模板是从带有自定义参数的 Amazon S3 URL 中获取的（PK1“” 表示模板内容中声明的参数的名称，PV1“” 表示参数的值。 也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。 如果堆栈创建失败，则会将其回滚（与指定相同-DisableRollback \$1false）。指定的通知 AENs 将收到已发布的堆栈相关事件。**  

```
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 参考 (V* 5) [CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Remove-CFNStack`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的堆栈。**  

```
Remove-CFNStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Resume-CFNUpdateRollback`。

**适用于 PowerShell V5 的工具**  
**示例 1：继续指定堆栈的回滚，该堆栈的状态应为“UPDATE\$1ROLLBACK\$1FAILED”。如果继续回滚成功，堆栈将进入“UPDATE\$1ROLLBACK\$1COMPLETE”状态。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Stop-CFNUpdateStack`。

**适用于 PowerShell V5 的工具**  
**示例 1：取消指定堆栈的更新。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CancelUpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Test-CFNStack`。

**适用于 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 CFNStack 中的[测试](https://docs.aws.amazon.com/powershell/v5/reference)参考 (V5)*。

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

以下代码示例演示了如何使用 `Test-CFNTemplate`。

**适用于 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 参考 (V* 5) [ValidateTemplate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

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

以下代码示例演示了如何使用 `Update-CFNStack`。

**适用于 PowerShell V5 的工具**  
**示例 1：使用指定的模板和自定义参数更新堆栈 “MyStack”。 'PK1' 表示模板中声明的参数的名称，而 'PV1' 表示其值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**示例 2：使用指定的模板和自定义参数更新堆栈 “MyStack”。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**示例 3：使用指定的模板和自定义参数更新堆栈 “MyStack”。 'PK1' 表示模板中声明的参数的名称，而 'PV2' 表示其值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**示例 4：使用从 Amazon S3 获得的指定模板和自定义参数更新堆栈 “MyStack”。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用从 Amazon S3 获取的指定模板和自定义参数更新堆栈 “MyStack”（在本示例中假设该堆栈包含 IAM 资源）。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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 参考 (V* 5) [UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Wait-CFNStack`
<a name="cloudformation_Wait-CFNStack_powershell_topic"></a>

以下代码示例演示了如何使用 `Wait-CFNStack`。

**适用于 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](https://docs.aws.amazon.com/powershell/v5/reference) *Cmdlet 参考 (V5)*。CFNStack

# CloudFront 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_cloudfront_code_examples"></a>

以下代码示例向您展示了如何使用带 CloudFront的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-CFCloudFrontOriginAccessIdentity`
<a name="cloudfront_GetCloudFrontOriginAccessIdentity_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFCloudFrontOriginAccessIdentity`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回由-Id 参数指定的特定亚马逊 CloudFront 源访问身份。尽管不需要 -Id 参数，但如果您不指定该参数，则不会返回任何结果。**  

```
Get-CFCloudFrontOriginAccessIdentity -Id E3XXXXXXXXXXRT
```
**输出**：  

```
      CloudFrontOriginAccessIdentityConfig    Id                                      S3CanonicalUserId
      ------------------------------------    --                                      -----------------
      Amazon.CloudFront.Model.CloudFrontOr... E3XXXXXXXXXXRT                          4b6e...
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetCloudFrontOriginAccessIdentity](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFCloudFrontOriginAccessIdentityConfig`
<a name="cloudfront_GetCloudFrontOriginAccessIdentityConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFCloudFrontOriginAccessIdentityConfig`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回有关单个 Amazon CloudFront 源访问身份的配置信息，该身份由-Id 参数指定。如果未指定 -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 参考 (V* 5) [GetCloudFrontOriginAccessIdentityConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFCloudFrontOriginAccessIdentityList`
<a name="cloudfront_ListCloudFrontOriginAccessIdentities_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFCloudFrontOriginAccessIdentityList`。

**适用于 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 参考 (V* 5) [ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFDistribution`
<a name="cloudfront_GetDistribution_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFDistribution`。

**适用于 PowerShell V5 的工具**  
**示例 1：检索有关特定分配的信息。**  

```
Get-CFDistribution -Id EXAMPLE0000ID
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetDistribution](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFDistributionConfig`
<a name="cloudfront_GetDistributionConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFDistributionConfig`。

**适用于 PowerShell V5 的工具**  
**示例 1：检索有关特定分配的配置。**  

```
Get-CFDistributionConfig -Id EXAMPLE0000ID
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetDistributionConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFDistributionList`
<a name="cloudfront_ListDistributions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFDistributionList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回分配。**  

```
Get-CFDistributionList
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListDistributions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CFDistribution`
<a name="cloudfront_CreateDistribution_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CFDistribution`。

**适用于 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 参考 (V* 5) [CreateDistribution](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CFInvalidation`
<a name="cloudfront_CreateInvalidation_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CFInvalidation`。

**适用于 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 参考 (V* 5) [CreateInvalidation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CFSignedCookie`
<a name="cloudfront_New-CFSignedCookie_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CFSignedCookie`。

**适用于 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) 中的 “新增-C CFSigned* [ookie](https://docs.aws.amazon.com/powershell/v5/reference)”。

### `New-CFSignedUrl`
<a name="cloudfront_New-CFSignedUrl_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CFSignedUrl`。

**适用于 PowerShell V5 的工具**  
**示例 1：使用标准策略创建指向指定资源的签名 url。url 的有效期为 1 小时。包含签名 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 参考文档 (V* 5) 中的[新建CFSigned网址](https://docs.aws.amazon.com/powershell/v5/reference)。

# CloudTrail 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_cloudtrail_code_examples"></a>

以下代码示例向您展示了如何使用带 CloudTrail的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Find-CTEvent`
<a name="cloudtrail_LookupEvents_powershell_topic"></a>

以下代码示例演示了如何使用 `Find-CTEvent`。

**适用于 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 参考 (V* 5) [LookupEvents](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CTTrail`
<a name="cloudtrail_DescribeTrails_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CTTrail`。

**适用于 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 参考 (V* 5) [DescribeTrails](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CTTrailStatus`
<a name="cloudtrail_GetTrailStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CTTrailStatus`。

**适用于 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 参考 (V* 5) [GetTrailStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CTTrail`
<a name="cloudtrail_CreateTrail_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CTTrail`。

**适用于 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 参考 (V* 5) [CreateTrail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CTTrail`
<a name="cloudtrail_DeleteTrail_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CTTrail`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的跟踪。在运行此命令之前，系统会提示您进行确认。要禁止确认，请添加 -Force 开关参数。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteTrail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-CTLogging`
<a name="cloudtrail_StartLogging_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-CTLogging`。

**适用于 PowerShell V5 的工具**  
**示例 1：开始为名为 “myExampleTrail” 的跟踪记录 AWS API 调用和日志文件传输。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Start-CTLogging -Name myExampleTrail
```
**示例 2：开始记录在当前外壳默认区域（在本例中为法兰克福 (eu-central-1) 区域）中创建的跟踪 AWS API 调用和日志文件传输。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StartLogging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-CTLogging`
<a name="cloudtrail_StopLogging_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-CTLogging`。

**适用于 PowerShell V5 的工具**  
**示例 1：暂停记录名为 “myExampleTrail” 的跟踪的 AWS API 调用和日志文件传输。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Stop-CTLogging -Name myExampleTrail
```
**示例 2：暂停记录在当前外壳默认区域（在本例中为法兰克福（eu-central-1）区域）中创建的跟踪 AWS API 调用和日志文件传输。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StopLogging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CTTrail`
<a name="cloudtrail_UpdateTrail_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CTTrail`。

**适用于 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 参考 (V* 5) [UpdateTrail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# CloudWatch 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_cloudwatch_code_examples"></a>

以下代码示例向您展示了如何使用带 CloudWatch的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-CWDashboard`
<a name="cloudwatch_GetDashboard_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CWDashboard`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定控制面板的正文 arn。**  

```
Get-CWDashboard -DashboardName Dashboard1
```
**输出**：  

```
DashboardArn                                          DashboardBody
------------                                          -------------
arn:aws:cloudwatch::123456789012:dashboard/Dashboard1 {...
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetDashboard](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CWDashboardList`
<a name="cloudwatch_ListDashboards_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CWDashboardList`。

**适用于 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 参考 (V* 5) [ListDashboards](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CWDashboard`
<a name="cloudwatch_DeleteDashboards_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CWDashboard`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的控制面板，继续操作前提示确认。要绕过确认，请在命令中添加 -Force 开关。**  

```
Remove-CWDashboard -DashboardName Dashboard1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteDashboards](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-CWDashboard`
<a name="cloudwatch_PutDashboard_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-CWDashboard`。

**适用于 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 参考 (V* 5) [PutDashboard](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-CWMetricData`
<a name="cloudwatch_PutMetricData_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-CWMetricData`。

**适用于 PowerShell V5 的工具**  
**示例 1：创建新 MetricDatum 对象并将其写入 Amazon Web Serv CloudWatch ices 指标。**  

```
### 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 参考 (V* 5) [PutMetricData](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# CodeCommit 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_codecommit_code_examples"></a>

以下代码示例向您展示了如何使用带 CodeCommit的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-CCBranch`
<a name="codecommit_GetBranch_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CCBranch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取有关指定存储库的指定分支的信息。**  

```
Get-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch
```
**输出**：  

```
BranchName                              CommitId
----------                              --------
MyNewBranch                             7763222d...561fc9c9
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBranch](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CCBranchList`
<a name="codecommit_ListBranches_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CCBranchList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定存储库的分支名称的列表。**  

```
Get-CCBranchList -RepositoryName MyDemoRepo
```
**输出**：  

```
master
MyNewBranch
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListBranches](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CCRepository`
<a name="codecommit_GetRepository_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CCRepository`。

**适用于 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 参考 (V* 5) [GetRepository](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CCRepositoryBatch`
<a name="codecommit_BatchGetRepositories_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CCRepositoryBatch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例确认已找到和未找到哪些指定的存储库。**  

```
Get-CCRepositoryBatch -RepositoryName MyDemoRepo, MyNewRepo, AMissingRepo
```
**输出**：  

```
Repositories                            RepositoriesNotFound
------------                            --------------------
{MyDemoRepo, MyNewRepo}                {AMissingRepo}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [BatchGetRepositories](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CCRepositoryList`
<a name="codecommit_ListRepositories_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CCRepositoryList`。

**适用于 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 参考 (V* 5) [ListRepositories](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CCBranch`
<a name="codecommit_CreateBranch_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CCBranch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用指定存储库的指定名称和指定的提交 ID 创建一个新分支。**  

```
New-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch -CommitId 7763222d...561fc9c9
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateBranch](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CCRepository`
<a name="codecommit_CreateRepository_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CCRepository`。

**适用于 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 参考 (V* 5) [CreateRepository](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CCRepository`
<a name="codecommit_DeleteRepository_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CCRepository`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例强制删除指定的存储库。在继续操作之前，该命令将提示进行确认。添加 -Force 参数可在不提示的情况下删除存储库。**  

```
Remove-CCRepository -RepositoryName MyDemoRepo
```
**输出**：  

```
43ef2443-3372-4b12-9e78-65c27EXAMPLE
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteRepository](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CCDefaultBranch`
<a name="codecommit_UpdateDefaultBranch_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CCDefaultBranch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定存储库的默认分支更改为指定的分支。**  

```
Update-CCDefaultBranch -RepositoryName MyDemoRepo -DefaultBranchName MyNewBranch
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateDefaultBranch](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CCRepositoryDescription`
<a name="codecommit_UpdateRepositoryDescription_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CCRepositoryDescription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更改指定存储库的描述。**  

```
Update-CCRepositoryDescription -RepositoryName MyDemoRepo -RepositoryDescription "This is an updated description."
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateRepositoryDescription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CCRepositoryName`
<a name="codecommit_UpdateRepositoryName_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CCRepositoryName`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更改指定存储库的名称。**  

```
Update-CCRepositoryName -NewName MyDemoRepo2 -OldName MyDemoRepo
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateRepositoryName](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# CodeDeploy 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_codedeploy_code_examples"></a>

以下代码示例向您展示了如何使用带 CodeDeploy的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-CDOnPremiseInstanceTag`
<a name="codedeploy_AddTagsToOnPremisesInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-CDOnPremiseInstanceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为指定的本地实例添加具有指定键和值的本地实例标签。**  

```
Add-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AddTagsToOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDApplication`
<a name="codedeploy_GetApplication_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDApplication`。

**适用于 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 参考 (V* 5) [GetApplication](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDApplicationBatch`
<a name="codedeploy_BatchGetApplications_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDApplicationBatch`。

**适用于 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 参考 (V* 5) [BatchGetApplications](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDApplicationList`
<a name="codedeploy_ListApplications_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDApplicationList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取可用应用程序的列表。**  

```
Get-CDApplicationList
```
**输出**：  

```
CodeDeployDemoApplication
CodePipelineDemoApplication
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListApplications](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDApplicationRevision`
<a name="codedeploy_GetApplicationRevision_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDApplicationRevision`。

**适用于 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 参考 (V* 5) [GetApplicationRevision](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDApplicationRevisionList`
<a name="codedeploy_ListApplicationRevisions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDApplicationRevisionList`。

**适用于 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 参考 (V* 5) [ListApplicationRevisions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeployment`
<a name="codedeploy_GetDeployment_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeployment`。

**适用于 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 参考 (V* 5) [GetDeployment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentBatch`
<a name="codedeploy_BatchGetDeployments_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentBatch`。

**适用于 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 参考 (V* 5) [BatchGetDeployments](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentConfig`
<a name="codedeploy_GetDeploymentConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentConfig`。

**适用于 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 参考 (V* 5) [GetDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentConfigList`
<a name="codedeploy_ListDeploymentConfigs_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentConfigList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取可用部署配置的列表。**  

```
Get-CDDeploymentConfigList
```
**输出**：  

```
ThreeQuartersHealthy
CodeDeployDefault.OneAtATime
CodeDeployDefault.AllAtOnce
CodeDeployDefault.HalfAtATime
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListDeploymentConfigs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentGroup`
<a name="codedeploy_GetDeploymentGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentGroup`。

**适用于 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 参考 (V* 5) [GetDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentGroupList`
<a name="codedeploy_ListDeploymentGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentGroupList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定应用程序的部署组的列表。**  

```
Get-CDDeploymentGroupList -ApplicationName CodeDeployDemoApplication
```
**输出**：  

```
ApplicationName              DeploymentGroups                                    NextToken
---------------              ----------------                                    ---------
CodeDeployDemoApplication    {CodeDeployDemoFleet, CodeDeployProductionFleet}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListDeploymentGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentInstance`
<a name="codedeploy_GetDeploymentInstance_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentInstance`。

**适用于 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 参考 (V* 5) [GetDeploymentInstance](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentInstanceList`
<a name="codedeploy_ListDeploymentInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentInstanceList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定部署 IDs 的实例列表。**  

```
Get-CDDeploymentInstanceList -DeploymentId d-QZMRGSTEX
```
**输出**：  

```
i-254e22EX
i-274e22EX
i-3b4e22EX
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListDeploymentInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDDeploymentList`
<a name="codedeploy_ListDeployments_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDDeploymentList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定应用程序和部署 IDs 组的部署列表。**  

```
Get-CDDeploymentList -ApplicationName CodeDeployDemoApplication -DeploymentGroupName CodeDeployDemoFleet
```
**输出**：  

```
d-QZMRGSTEX
d-RR0T5KTEX
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListDeployments](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDOnPremiseInstance`
<a name="codedeploy_GetOnPremisesInstance_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDOnPremiseInstance`。

**适用于 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 参考 (V* 5) [GetOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDOnPremiseInstanceBatch`
<a name="codedeploy_BatchGetOnPremisesInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDOnPremiseInstanceBatch`。

**适用于 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 参考 (V* 5) [BatchGetOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CDOnPremiseInstanceList`
<a name="codedeploy_ListOnPremisesInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CDOnPremiseInstanceList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取可用本地实例名称的列表。**  

```
Get-CDOnPremiseInstanceList
```
**输出**：  

```
AssetTag12010298EX
AssetTag12010298EX-2
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CDApplication`
<a name="codedeploy_CreateApplication_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CDApplication`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用指定名称创建新的应用程序。**  

```
New-CDApplication -ApplicationName MyNewApplication
```
**输出**：  

```
f19e4b61-2231-4328-b0fd-e57f5EXAMPLE
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateApplication](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CDDeployment`
<a name="codedeploy_CreateDeployment_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CDDeployment`。

**适用于 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 实例标签组，实例必须通过这些标签进行标识，才能将其包含在 blue/green 部署的替换环境中。**  

```
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 参考 (V* 5) [CreateDeployment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CDDeploymentConfig`
<a name="codedeploy_CreateDeploymentConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CDDeploymentConfig`。

**适用于 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 参考 (V* 5) [CreateDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CDDeploymentGroup`
<a name="codedeploy_CreateDeploymentGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CDDeploymentGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为指定的应用程序创建具有指定名称、自动扩缩组、部署配置、标签和服务角色的部署组。**  

```
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 实例标签组，实例必须通过这些标签进行标识，才能将其包含在 blue/green 部署的替换环境中。**  

```
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 参考 (V* 5) [CreateDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-CDApplicationRevision`
<a name="codedeploy_RegisterApplicationRevision_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-CDApplicationRevision`。

**适用于 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 参考 (V* 5) [RegisterApplicationRevision](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-CDOnPremiseInstance`
<a name="codedeploy_RegisterOnPremisesInstance_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-CDOnPremiseInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用指定的名称和 IAM 用户注册本地实例。**  

```
Register-CDOnPremiseInstance -IamUserArn arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser -InstanceName AssetTag12010298EX
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RegisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CDApplication`
<a name="codedeploy_DeleteApplication_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CDApplication`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除具有指定名称的应用程序。在继续操作之前，该命令将提示进行确认。添加 -Force 参数可在不提示的情况下删除应用程序。**  

```
Remove-CDApplication -ApplicationName MyNewApplication
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteApplication](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CDDeploymentConfig`
<a name="codedeploy_DeleteDeploymentConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CDDeploymentConfig`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除具有指定名称的部署配置。在继续操作之前，该命令将提示进行确认。添加 -Force 参数可在不提示的情况下删除部署配置。**  

```
Remove-CDDeploymentConfig -DeploymentConfigName AtLeastTwoHealthyHosts
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CDDeploymentGroup`
<a name="codedeploy_DeleteDeploymentGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CDDeploymentGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定应用程序的具有指定名称的部署组。在继续操作之前，该命令将提示进行确认。添加 -Force 参数可在不提示的情况下删除部署组。**  

```
Remove-CDDeploymentGroup -ApplicationName MyNewApplication -DeploymentGroupName MyNewDeploymentGroup
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CDOnPremiseInstanceTag`
<a name="codedeploy_RemoveTagsFromOnPremisesInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CDOnPremiseInstanceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为具有指定名称的本地实例删除指定的标签。在继续操作之前，该命令将提示进行确认。添加 -Force 参数可在不提示的情况下删除标签。**  

```
Remove-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RemoveTagsFromOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-CDDeployment`
<a name="codedeploy_StopDeployment_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-CDDeployment`。

**适用于 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 参考 (V* 5) [StopDeployment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-CDOnPremiseInstance`
<a name="codedeploy_DeregisterOnPremisesInstance_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-CDOnPremiseInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例取消注册具有指定名称的本地实例。**  

```
Unregister-CDOnPremiseInstance -InstanceName AssetTag12010298EX
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeregisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CDApplication`
<a name="codedeploy_UpdateApplication_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CDApplication`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更改指定应用程序的名称。**  

```
Update-CDApplication -ApplicationName MyNewApplication -NewApplicationName MyNewApplication-2
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateApplication](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CDDeploymentGroup`
<a name="codedeploy_UpdateDeploymentGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CDDeploymentGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更改指定应用程序的指定部署组的名称。**  

```
Update-CDDeploymentGroup -ApplicationName MyNewApplication -CurrentDeploymentGroupName MyNewDeploymentGroup -NewDeploymentGroupName MyNewDeploymentGroup-2
```
**示例 2：此示例说明如何指定 EC2 实例标签组，实例必须通过这些标签进行标识，才能将其包含在 blue/green 部署的替换环境中。**  

```
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 参考 (V* 5) [UpdateDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# CodePipeline 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_codepipeline_code_examples"></a>

以下代码示例向您展示了如何使用带 CodePipeline的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Confirm-CPJob`
<a name="codepipeline_AcknowledgeJob_powershell_topic"></a>

以下代码示例演示了如何使用 `Confirm-CPJob`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定作业的状态。**  

```
Confirm-CPJob -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE -Nonce 3
```
**输出**：  

```
Value
-----
InProgress
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AcknowledgeJob](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-CPStageTransition`
<a name="codepipeline_DisableStageTransition_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-CPStageTransition`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例对指定管道中的指定阶段禁用入站转换。**  

```
Disable-CPStageTransition -PipelineName CodePipelineDemo -Reason "Disabling temporarily." -StageName Beta -TransitionType Inbound
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableStageTransition](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-CPStageTransition`
<a name="codepipeline_EnableStageTransition_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-CPStageTransition`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例对指定管道中的指定阶段启用入站转换。**  

```
Enable-CPStageTransition -PipelineName CodePipelineDemo -StageName Beta -TransitionType Inbound
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableStageTransition](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CPActionType`
<a name="codepipeline_ListActionTypes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CPActionType`。

**适用于 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 参考 (V* 5) [ListActionTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CPActionableJobList`
<a name="codepipeline_PollForJobs_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CPActionableJobList`。

**适用于 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 参考 (V* 5) [PollForJobs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CPJobDetail`
<a name="codepipeline_GetJobDetails_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CPJobDetail`。

**适用于 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 参考 (V* 5) [GetJobDetails](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CPPipeline`
<a name="codepipeline_GetPipeline_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CPPipeline`。

**适用于 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 参考 (V* 5) [GetPipeline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CPPipelineList`
<a name="codepipeline_ListPipelines_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CPPipelineList`。

**适用于 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 参考 (V* 5) [ListPipelines](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CPPipelineState`
<a name="codepipeline_GetPipelineState_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CPPipelineState`。

**适用于 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 参考 (V* 5) [GetPipelineState](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CPCustomActionType`
<a name="codepipeline_CreateCustomActionType_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CPCustomActionType`。

**适用于 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 参考 (V* 5) [CreateCustomActionType](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CPPipeline`
<a name="codepipeline_CreatePipeline_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CPPipeline`。

**适用于 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 参考 (V* 5) [CreatePipeline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CPCustomActionType`
<a name="codepipeline_DeleteCustomActionType_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CPCustomActionType`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定的自定义操作。在继续操作之前，该命令将提示进行确认。添加 -Force 参数可在不提示的情况下删除自定义操作。**  

```
Remove-CPCustomActionType -Category Build -Provider MyBuildProviderName -Version 1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteCustomActionType](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CPPipeline`
<a name="codepipeline_DeletePipeline_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CPPipeline`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定的管道。在继续操作之前，该命令将提示进行确认。添加 -Force 参数可在不提示的情况下删除管道。**  

```
Remove-CPPipeline -Name CodePipelineDemo
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeletePipeline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-CPPipelineExecution`
<a name="codepipeline_StartPipelineExecution_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-CPPipelineExecution`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例开始运行指定的管道。**  

```
Start-CPPipelineExecution -Name CodePipelineDemo
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StartPipelineExecution](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CPPipeline`
<a name="codepipeline_UpdatePipeline_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CPPipeline`。

**适用于 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 参考 (V* 5) [UpdatePipeline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 V5 的工具的 Amazon Cognito 身份示例 PowerShell
<a name="powershell_cognito-identity_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon Cognito Identity 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-CGIIdentityPool`
<a name="cognito-identity_DescribeIdentityPool_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CGIIdentityPool`。

**适用于 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 参考 (V* 5) [DescribeIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CGIIdentityPoolList`
<a name="cognito-identity_ListIdentityPools_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CGIIdentityPoolList`。

**适用于 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 参考 (V* 5) [ListIdentityPools](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CGIIdentityPoolRole`
<a name="cognito-identity_GetIdentityPoolRoles_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CGIIdentityPoolRole`。

**适用于 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 参考 (V* 5) [GetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-CGIIdentityPool`
<a name="cognito-identity_CreateIdentityPool_powershell_topic"></a>

以下代码示例演示了如何使用 `New-CGIIdentityPool`。

**适用于 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 参考 (V* 5) [CreateIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CGIIdentityPool`
<a name="cognito-identity_DeleteIdentityPool_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CGIIdentityPool`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除特定身份池。**  

```
Remove-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-CGIIdentityPoolRole`
<a name="cognito-identity_SetIdentityPoolRoles_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-CGIIdentityPoolRole`。

**适用于 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 参考 (V* 5) [SetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-CGIIdentityPool`
<a name="cognito-identity_UpdateIdentityPool_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-CGIIdentityPool`。

**适用于 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 参考 (V* 5) [UpdateIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS Config 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_config-service_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS Config的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-CFGResourceTag`
<a name="config-service_TagResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-CFGResourceTag`。

**适用于 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 参考 (V* 5) [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGAggregateComplianceByConfigRuleList`
<a name="config-service_DescribeAggregateComplianceByConfigRules_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregateComplianceByConfigRuleList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从给定配置规则 ConfigurationAggregator 的 “kaju” 筛选和规则的 “合规性” expands/returns 中获取详细信息。**  

```
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 参考 (V* 5) [DescribeAggregateComplianceByConfigRules](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGAggregateComplianceDetailsByConfigRule`
<a name="config-service_GetAggregateComplianceDetailsByConfigRule_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregateComplianceDetailsByConfigRule`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回评估结果，为给定账户、聚合器、区域和 AWS 配置规则的 Config 规则 “desired-instance-type” 选择带有资源 ID 和资源类型的输出，这些输出处于 “合规” 状态**  

```
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 参考 (V* 5) [GetAggregateComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGAggregateConfigRuleComplianceSummary`
<a name="config-service_GetAggregateConfigRuleComplianceSummary_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregateConfigRuleComplianceSummary`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回给定聚合器的不合规规则数。**  

```
(Get-CFGAggregateConfigRuleComplianceSummary -ConfigurationAggregatorName raju).AggregateComplianceCounts.ComplianceSummary.NonCompliantResourceCount
```
**输出**：  

```
CapExceeded CappedCount
----------- -----------
False       5
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetAggregateConfigRuleComplianceSummary](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGAggregateDiscoveredResourceCount`
<a name="config-service_GetAggregateDiscoveredResourceCounts_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregateDiscoveredResourceCount`。

**适用于 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 参考 (V* 5) [GetAggregateDiscoveredResourceCounts](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGAggregateDiscoveredResourceList`
<a name="config-service_ListAggregateDiscoveredResources_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregateDiscoveredResourceList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回在“Ireland”聚合器中聚合的给定资源类型的资源标识符。有关资源类型列表，请查看 https://docs.aws.amazon.com/sdkfornet/ v4/ apidocs/index.html?page=ConfigService/TConfigServiceResourceType .html&t ConfigService ocid=amazon\$1 \$1。ResourceType**  

```
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：此示例返回使用区域 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 参考 (V* 5) [ListAggregateDiscoveredResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGAggregateResourceConfig`
<a name="config-service_GetAggregateResourceconfig-service_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregateResourceConfig`。

**适用于 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-servic](https://docs.aws.amazon.com/powershell/v5/reference) e。

### `Get-CFGAggregateResourceConfigBatch`
<a name="config-service_BatchGetAggregateResourceconfig-service_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregateResourceConfigBatch`。

**适用于 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-servic](https://docs.aws.amazon.com/powershell/v5/reference) e。

### `Get-CFGAggregationAuthorizationList`
<a name="config-service_DescribeAggregationAuthorizations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGAggregationAuthorizationList`。

**适用于 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 参考 (V* 5) [DescribeAggregationAuthorizations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGComplianceByConfigRule`
<a name="config-service_DescribeComplianceByConfigRule_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGComplianceByConfigRule`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例检索规则的合规性详细信息，该规则当前没有评估结果 ebs-optimized-instance，因此它返回 INSUFKIENT\$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 参考 (V* 5) [DescribeComplianceByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGComplianceByResource`
<a name="config-service_DescribeComplianceByResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGComplianceByResource`。

**适用于 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 参考 (V* 5) [DescribeComplianceByResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGComplianceDetailsByConfigRule`
<a name="config-service_GetComplianceDetailsByConfigRule_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGComplianceDetailsByConfigRule`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取规则的评估结果 access-keys-rotated并返回按合规类型分组的输出**  

```
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：此示例查询合规资源的规则 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 参考 (V* 5) [GetComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGComplianceDetailsByResource`
<a name="config-service_GetComplianceDetailsByResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGComplianceDetailsByResource`。

**适用于 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 参考 (V* 5) [GetComplianceDetailsByResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGComplianceSummaryByConfigRule`
<a name="config-service_GetComplianceSummaryByConfigRule_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGComplianceSummaryByConfigRule`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回不合规的 Config 规则的数量。**  

```
Get-CFGComplianceSummaryByConfigRule -Select ComplianceSummary.NonCompliantResourceCount
```
**输出**：  

```
CapExceeded CappedCount
----------- -----------
False       9
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetComplianceSummaryByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGComplianceSummaryByResourceType`
<a name="config-service_GetComplianceSummaryByResourceType_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGComplianceSummaryByResourceType`。

**适用于 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 参考 (V* 5) [GetComplianceSummaryByResourceType](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGConfigRule`
<a name="config-service_DescribeConfigRules_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGConfigRule`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出账户的配置规则以及选定属性。**  

```
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 参考 (V* 5) [DescribeConfigRules](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGConfigRuleEvaluationStatus`
<a name="config-service_DescribeConfigRuleEvaluationStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGConfigRuleEvaluationStatus`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回给定配置规则的状态信息。**  

```
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 参考 (V* 5) [DescribeConfigRuleEvaluationStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGConfigurationAggregatorList`
<a name="config-service_DescribeConfigurationAggregators_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGConfigurationAggregatorList`。

**适用于 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 参考 (V* 5) [DescribeConfigurationAggregators](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGConfigurationAggregatorSourcesStatus`
<a name="config-service_DescribeConfigurationAggregatorSourcesStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGConfigurationAggregatorSourcesStatus`。

**适用于 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 参考 (V* 5) [DescribeConfigurationAggregatorSourcesStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGConfigurationRecorder`
<a name="config-service_DescribeConfigurationRecorders_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGConfigurationRecorder`。

**适用于 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 参考 (V* 5) [DescribeConfigurationRecorders](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGConfigurationRecorderStatus`
<a name="config-service_DescribeConfigurationRecorderStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGConfigurationRecorderStatus`。

**适用于 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 参考 (V* 5) [DescribeConfigurationRecorderStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGConformancePack`
<a name="config-service_DescribeConformancePacks_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGConformancePack`。

**适用于 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 参考 (V* 5) [DescribeConformancePacks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGDeliveryChannel`
<a name="config-service_DescribeDeliveryChannels_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGDeliveryChannel`。

**适用于 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 参考 (V* 5) [DescribeDeliveryChannels](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-CFGResourceTag`
<a name="config-service_ListTagsForResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-CFGResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出给定资源的关联标签**  

```
Get-CFGResourceTag -ResourceArn $rules[0].ConfigRuleArn
```
**输出**：  

```
Key     Value
---     -----
Version 1.3
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-CFGConformancePack`
<a name="config-service_DeleteConformancePack_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-CFGConformancePack`。

**适用于 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 参考 (V* 5) [DeleteConformancePack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-CFGConformancePack`
<a name="config-service_PutConformancePack_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-CFGConformancePack`。

**适用于 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 参考 (V* 5) [PutConformancePack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-CFGDeliveryChannel`
<a name="config-service_PutDeliveryChannel_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-CFGDeliveryChannel`。

**适用于 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 参考 (V* 5) [PutDeliveryChannel](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用 V5 工具的 De PowerShell vice Farm 示例
<a name="powershell_device-farm_code_examples"></a>

以下代码示例向您展示了如何使用带有 Device Farm 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `New-DFUpload`
<a name="device-farm_CreateUpload_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DFUpload`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为安卓应用创建 Dev AWS ice Farm 上传。您可以从 “新建列表” DFProject 或 “获取列表” 的输出中获取项目 ARN。DFProject使用新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 参考 (V* 5) [CreateUpload](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# Directory Service 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_directory-service_code_examples"></a>

以下代码示例向您展示了如何使用带 Directory Service的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-DSIpRoute`
<a name="directory-service_AddIpRoutes_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-DSIpRoute`。

**适用于 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 参考 (V* 5) [AddIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-DSResourceTag`
<a name="directory-service_AddTagsToResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-DSResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令将资源标签添加到指定的 Directory-id**  

```
Add-DSResourceTag -ResourceId d-123456ijkl -Tag @{Key="myTag"; Value="mytgValue"}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AddTagsToResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Approve-DSTrust`
<a name="directory-service_VerifyTrust_powershell_topic"></a>

以下代码示例演示了如何使用 `Approve-DSTrust`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例调用指定的 Trustid 的 Di AWS rectory Service VerifyTrust API 操作。**  

```
Approve-DSTrust -TrustId t-9067157123
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [VerifyTrust](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Confirm-DSSharedDirectory`
<a name="directory-service_AcceptSharedDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `Confirm-DSSharedDirectory`。

**适用于 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 参考 (V* 5) [AcceptSharedDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Connect-DSDirectory`
<a name="directory-service_ConnectDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `Connect-DSDirectory`。

**适用于 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 参考 (V* 5) [ConnectDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Deny-DSSharedDirectory`
<a name="directory-service_RejectSharedDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `Deny-DSSharedDirectory`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例拒绝从目录所有者账户中发送的目录共享请求。**  

```
Deny-DSSharedDirectory -SharedDirectoryId d-9067012345
```
**输出**：  

```
d-9067012345
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RejectSharedDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-DSDirectoryShare`
<a name="directory-service_UnshareDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-DSDirectoryShare`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例停止目录所有者和使用者账户之间的目录共享。**  

```
Disable-DSDirectoryShare -DirectoryId d-123456ijkl -UnshareTarget_Id 123456784321 -UnshareTarget_Type ACCOUNT
```
**输出**：  

```
d-9067012345
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UnshareDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-DSLDAPS`
<a name="directory-service_DisableLDAPS_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-DSLDAPS`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例停用对指定目录的 LDAP 安全调用。**  

```
Disable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  有关 API 详细信息，请参阅《AWS Tools for PowerShell Cmdlet Reference (V5)》**中的 [DisableLDAPS](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Disable-DSRadius`
<a name="directory-service_DisableRadius_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-DSRadius`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁用为 AD Connector 或 Microsoft AD 目录配置的 RADIUS 服务器。**  

```
Disable-DSRadius -DirectoryId d-123456ijkl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableRadius](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-DSSso`
<a name="directory-service_DisableSso_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-DSSso`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为目录禁用单点登录。**  

```
Disable-DSSso -DirectoryId d-123456ijkl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableSso](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-DSDirectoryShare`
<a name="directory-service_ShareDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-DSDirectoryShare`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用 Handshake 方法与另一个 AWS 账户共享您 AWS 账户中的指定目录。**  

```
Enable-DSDirectoryShare -DirectoryId d-123456ijkl -ShareTarget_Id 123456784321 -ShareMethod HANDSHAKE -ShareTarget_Type ACCOUNT
```
**输出**：  

```
d-9067012345
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ShareDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-DSLDAPS`
<a name="directory-service_EnableLDAPS_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-DSLDAPS`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例激活特定目录的开关以始终使用 LDAP 安全调用。**  

```
Enable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  有关 API 详细信息，请参阅《AWS Tools for PowerShell Cmdlet Reference (V5)》**中的 [EnableLDAPS](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Enable-DSRadius`
<a name="directory-service_EnableRadius_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-DSRadius`。

**适用于 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 参考 (V* 5) [EnableRadius](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-DSSso`
<a name="directory-service_EnableSso_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-DSSso`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为目录启用单点登录。**  

```
Enable-DSSso -DirectoryId d-123456ijkl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableSso](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSCertificate`
<a name="directory-service_DescribeCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSCertificate`。

**适用于 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 参考 (V* 5) [DescribeCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSCertificateList`
<a name="directory-service_ListCertificates_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSCertificateList`。

**适用于 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 参考 (V* 5) [ListCertificates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSConditionalForwarder`
<a name="directory-service_DescribeConditionalForwarders_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSConditionalForwarder`。

**适用于 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 参考 (V* 5) [DescribeConditionalForwarders](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSDirectory`
<a name="directory-service_DescribeDirectories_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSDirectory`。

**适用于 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 参考 (V* 5) [DescribeDirectories](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSDirectoryLimit`
<a name="directory-service_GetDirectoryLimits_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSDirectoryLimit`。

**适用于 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 参考 (V* 5) [GetDirectoryLimits](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSDomainControllerList`
<a name="directory-service_DescribeDomainControllers_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSDomainControllerList`。

**适用于 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 参考 (V* 5) [DescribeDomainControllers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSEventTopic`
<a name="directory-service_DescribeEventTopics_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSEventTopic`。

**适用于 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 参考 (V* 5) [DescribeEventTopics](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSIpRouteList`
<a name="directory-service_ListIpRoutes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSIpRouteList`。

**适用于 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 参考 (V* 5) [ListIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSLDAPSSetting`
<a name="directory-service_DescribeLDAPSSettings_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSLDAPSSetting`。

**适用于 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 参考文档 (V* 5) LDAPSSettings 中的[描述](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DSLogSubscriptionList`
<a name="directory-service_ListLogSubscriptions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSLogSubscriptionList`。

**适用于 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 参考 (V* 5) [ListLogSubscriptions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSResourceTag`
<a name="directory-service_ListTagsForResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令获取指定目录的所有标签。**  

```
Get-DSResourceTag -ResourceId d-123456ijkl
```
**输出**：  

```
Key   Value
---   -----
myTag myTagValue
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSSchemaExtension`
<a name="directory-service_ListSchemaExtensions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSSchemaExtension`。

**适用于 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 参考 (V* 5) [ListSchemaExtensions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSSharedDirectory`
<a name="directory-service_DescribeSharedDirectories_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSSharedDirectory`。

**适用于 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 参考 (V* 5) [DescribeSharedDirectories](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSSnapshot`
<a name="directory-service_DescribeSnapshots_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSSnapshot`。

**适用于 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 参考 (V* 5) [DescribeSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSSnapshotLimit`
<a name="directory-service_GetSnapshotLimits_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSSnapshotLimit`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令获取指定目录的手动快照限制。**  

```
Get-DSSnapshotLimit -DirectoryId d-123456ijkl
```
**输出**：  

```
ManualSnapshotsCurrentCount ManualSnapshotsLimit ManualSnapshotsLimitReached
--------------------------- -------------------- ---------------------------
0                           5                    False
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetSnapshotLimits](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DSTrust`
<a name="directory-service_DescribeTrusts_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DSTrust`。

**适用于 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 参考 (V* 5) [DescribeTrusts](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DSAlias`
<a name="directory-service_CreateAlias_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSAlias`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令为目录创建一个别名并将此别名分配给指定的 directory-id。**  

```
New-DSAlias -DirectoryId d-123456ijkl -Alias MyOrgName
```
**输出**：  

```
Alias     DirectoryId
-----     -----------
myorgname d-123456ijkl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateAlias](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DSComputer`
<a name="directory-service_CreateComputer_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSComputer`。

**适用于 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 参考 (V* 5) [CreateComputer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DSConditionalForwarder`
<a name="directory-service_CreateConditionalForwarder_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSConditionalForwarder`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在指定的 Di AWS rectory-ID 中创建条件转发器。**  

```
New-DSConditionalForwarder -DirectoryId d-123456ijkl -DnsIpAddr 172.31.36.96,172.31.10.56 -RemoteDomainName contoso.com
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DSDirectory`
<a name="directory-service_CreateDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSDirectory`。

**适用于 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 参考 (V* 5) [CreateDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DSLogSubscription`
<a name="directory-service_CreateLogSubscription_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSLogSubscription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建了一个订阅，用于将实时 Directory Service 域控制器安全日志转发到您的指定的 Amazon CloudWatch 日志组 AWS 账户。**  

```
New-DSLogSubscription -DirectoryId d-123456ijkl -LogGroupName /aws/directoryservice/d-123456ijkl-lan2.example.com
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateLogSubscription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DSMicrosoftAD`
<a name="directory-service_CreateMicrosoftAD_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSMicrosoftAD`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在中创建了新的 Microsoft 广告目录 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 参考 (V* 5) 中的 A [CreateMicrosoftD](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DSSnapshot`
<a name="directory-service_CreateSnapshot_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSSnapshot`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建目录快照**  

```
New-DSSnapshot -DirectoryId d-123456ijkl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DSTrust`
<a name="directory-service_CreateTrust_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DSTrust`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在您的托管 Microsoft AD 目录和现有的本地 AWS 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 参考 (V* 5) [CreateTrust](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-DSCertificate`
<a name="directory-service_RegisterCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-DSCertificate`。

**适用于 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 参考 (V* 5) [RegisterCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-DSEventTopic`
<a name="directory-service_RegisterEventTopic_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-DSEventTopic`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将目录作为发布者与 SNS 主题相关联。**  

```
Register-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RegisterEventTopic](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DSConditionalForwarder`
<a name="directory-service_DeleteConditionalForwarder_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DSConditionalForwarder`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除已为您的 D AWS irecotry 设置的条件转发器。**  

```
Remove-DSConditionalForwarder -DirectoryId d-123456ijkl -RemoteDomainName contoso.com
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DSDirectory`
<a name="directory-service_DeleteDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DSDirectory`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除 AWS 目录服务目录（简单 AD/Microsoft AD/AD 连接器）**  

```
Remove-DSDirectory -DirectoryId d-123456ijkl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DSIpRoute`
<a name="directory-service_RemoveIpRoutes_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DSIpRoute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令从 Directory-id 的已配置 IP 路由中移除指定的 IP。**  

```
Remove-DSIpRoute -DirectoryId d-123456ijkl -CidrIp 203.0.113.5/32
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RemoveIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DSLogSubscription`
<a name="directory-service_DeleteLogSubscription_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DSLogSubscription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令移除指定 Directory-id 的日志订阅**  

```
Remove-DSLogSubscription -DirectoryId d-123456ijkl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteLogSubscription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DSResourceTag`
<a name="directory-service_RemoveTagsFromResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DSResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令移除分配给指定 Directory-id 的资源标签**  

```
Remove-DSResourceTag -ResourceId d-123456ijkl -TagKey myTag
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DSSnapshot`
<a name="directory-service_DeleteSnapshot_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DSSnapshot`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例移除手动创建的快照。**  

```
Remove-DSSnapshot -SnapshotId s-9068b488kc
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DSTrust`
<a name="directory-service_DeleteTrust_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DSTrust`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了您的 AWS 托管 AD 目录与外部域之间现有的信任关系。**  

```
Get-DSTrust -DirectoryId d-123456ijkl -Select Trusts.TrustId | Remove-DSTrust
```
**输出**：  

```
t-9067157123
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteTrust](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Reset-DSUserPassword`
<a name="directory-service_ResetUserPassword_powershell_topic"></a>

以下代码示例演示了如何使用 `Reset-DSUserPassword`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例重置了在 Microsoft AD AWS 托管或 Simple AD Directory ADUser 中命名的 Active Direcotry 用户的密码**  

```
Reset-DSUserPassword -UserName ADuser -DirectoryId d-123456ijkl -NewPassword $Password
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResetUserPassword](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Restore-DSFromSnapshot`
<a name="directory-service_RestoreFromSnapshot_powershell_topic"></a>

以下代码示例演示了如何使用 `Restore-DSFromSnapshot`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用现有的目录快照还原目录。**  

```
Restore-DSFromSnapshot -SnapshotId s-9068b488kc
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RestoreFromSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-DSDomainControllerCount`
<a name="directory-service_UpdateNumberOfDomainControllers_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-DSDomainControllerCount`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定 directory-id 的域控制器数量设置为 3。**  

```
Set-DSDomainControllerCount -DirectoryId d-123456ijkl -DesiredNumber 3
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateNumberOfDomainControllers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-DSSchemaExtension`
<a name="directory-service_StartSchemaExtension_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-DSSchemaExtension`。

**适用于 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 参考 (V* 5) [StartSchemaExtension](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-DSSchemaExtension`
<a name="directory-service_CancelSchemaExtension_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-DSSchemaExtension`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例对 Microsoft AD 目录取消正在进行的架构扩展。**  

```
Stop-DSSchemaExtension -DirectoryId d-123456ijkl -SchemaExtensionId e-9067306643
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CancelSchemaExtension](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-DSCertificate`
<a name="directory-service_DeregisterCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-DSCertificate`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从系统中删除为受保护的 LDAP 连接注册的证书。**  

```
Unregister-DSCertificate -DirectoryId d-123456ijkl -CertificateId c-906731e34f
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeregisterCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-DSEventTopic`
<a name="directory-service_DeregisterEventTopic_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-DSEventTopic`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例取消指定的目录作为指定 SNS 主题的发布者。**  

```
Unregister-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeregisterEventTopic](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-DSConditionalForwarder`
<a name="directory-service_UpdateConditionalForwarder_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-DSConditionalForwarder`。

**适用于 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 参考 (V* 5) [UpdateConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-DSRadius`
<a name="directory-service_UpdateRadius_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-DSRadius`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新 AD Connector 或 Microsoft AD 目录的 RADIUS 服务器信息。**  

```
Update-DSRadius -DirectoryId d-123456ijkl -RadiusSettings_RadiusRetry 3
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateRadius](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-DSTrust`
<a name="directory-service_UpdateTrust_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-DSTrust`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定信任 ID 的 SelectiveAuth 参数从 “已禁用” 更新为 “启用”。**  

```
Update-DSTrust -TrustId t-9067157123 -SelectiveAuth Enabled
```
**输出**：  

```
RequestId                            TrustId
---------                            -------
138864a7-c9a8-4ad1-a828-eae479e85b45 t-9067157123
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateTrust](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS DMS 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_database-migration-service_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS DMS的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `New-DMSReplicationTask`
<a name="database-migration-service_CreateReplicationTask_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DMSReplicationTask`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建了一个新的 AWS 数据库迁移服务（Database Migration Service）复制任务，该任务使用 CdcStartTime 代替 CdcStartPosition。设置 MigrationType 为 full-load-and-cdc “”，这意味着目标表必须为空。新任务使用一个标签进行标记，该标签的键为 Stage，键值为 Test。有关此 cmdlet 使用的值的更多信息，请参阅《数据库迁移服务用户指南》https://docs.aws.amazon.com/dms/latest/userguide/CHAP中的创建任务 (\$1tasks.creating.html)。 AWS **  

```
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 参考 (V* 5) [CreateReplicationTask](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 V5 的工具的 DynamoDB 示例 PowerShell
<a name="powershell_dynamodb_code_examples"></a>

以下代码示例向您展示了如何使用带有 DynamoDB 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-DDBIndexSchema`
<a name="dynamodb_Add-DDBIndexSchema_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-DDBIndexSchema`。

**适用于 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 参考 (V* 5) 中的[添加DDBIndex架构](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Add-DDBKeySchema`
<a name="dynamodb_Add-DDBKeySchema_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-DDBKeySchema`。

**适用于 PowerShell V5 的工具**  
**示例 1：创建一个空 TableSchema 对象，并在将 TableSchema 对象写入管道之前，使用指定的密钥数据向其添加键和属性定义条目。默认情况下，键类型声明为 “HASH”；使用值为 “RANGE” 的-KeyType 参数来声明范围键。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**输出**：  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
**示例 2：在将对象写入管道之前，向提供的 TableSchema 对象添加新的键和属性定义条目。 TableSchema 默认情况下，键类型声明为 “HASH”；使用值为 “RANGE” 的-KeyType 参数来声明范围键。也可以使用-Schema 参数提供该 TableSchema 对象。**  

```
New-DDBTableSchema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**输出**：  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) 中的[添加DDBKey架构](https://docs.aws.amazon.com/powershell/v5/reference)。

### `ConvertFrom-DDBItem`
<a name="dynamodb_ConvertFrom-DDBItem_powershell_topic"></a>

以下代码示例演示了如何使用 `ConvertFrom-DDBItem`。

**适用于 PowerShell V5 的工具**  
**示例 1： ConvertFrom-DDBItem 用于将结果 Get-DDBItem 从 D AttributeValues ynamoDB 的哈希表转换为字符串和双精度等常见类型的哈希表。**  

```
@{
    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 参考 (V* 5) DDBItem 中的 [ConvertFrom-](https://docs.aws.amazon.com/powershell/v5/reference)。

### `ConvertTo-DDBItem`
<a name="dynamodb_ConvertTo-DDBItem_powershell_topic"></a>

以下代码示例演示了如何使用 `ConvertTo-DDBItem`。

**适用于 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 参考 (V* 5) DDBItem 中的 [ConvertTo-](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-DDBBatchItem`
<a name="dynamodb_BatchGetItem_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DDBBatchItem`。

**适用于 PowerShell V5 的工具**  
**示例 1：从 DynamoDB 表格 “音乐” 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 参考 (V* 5) [BatchGetItem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DDBItem`
<a name="dynamodb_GetItem_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DDBItem`。

**适用于 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 参考 (V* 5) [GetItem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DDBTable`
<a name="dynamodb_DescribeTable_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DDBTable`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定表的详细信息。**  

```
Get-DDBTable -TableName "myTable"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-DDBTableList`
<a name="dynamodb_ListTables_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-DDBTableList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回所有表的详细信息，自动迭代，直到服务指示不存在其它表。**  

```
Get-DDBTableList
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListTables](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Invoke-DDBQuery`
<a name="dynamodb_Query_powershell_topic"></a>

以下代码示例演示了如何使用 `Invoke-DDBQuery`。

**适用于 PowerShell V5 的工具**  
**示例 1：调用一个查询，返回指定和艺术家的 DynamoDB 项目。 SongTitle **  

```
$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 Reference (V5)》**中的 [Query](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Invoke-DDBScan`
<a name="dynamodb_Scan_powershell_topic"></a>

以下代码示例演示了如何使用 `Invoke-DDBScan`。

**适用于 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 大于或等于 9 的项目。**  

```
$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 Reference (V5)》**中的 [Scan](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-DDBTable`
<a name="dynamodb_CreateTable_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DDBTable`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建了一个名为 Thread 的表，该表的主键由 'ForumName'（键类型哈希）和 'Subject'（键类型范围）组成。用于构造表的架构可以通过管道传输到所示的每个 cmdlet 中，也可以使用 -Schema 参数指定。**  

```
$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)。用于构造表的架构可以通过管道传输到所示的每个 cmdlet 中，也可以使用 -Schema 参数指定。**  

```
$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'（键类型范围）组成，还有一个本地二级索引。如果管道或-DDBKey S DDBIndex chema参数未提供新 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 参考 (V* 5) [CreateTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-DDBTableSchema`
<a name="dynamodb_New-DDBTableSchema_powershell_topic"></a>

以下代码示例演示了如何使用 `New-DDBTableSchema`。

**适用于 PowerShell V5 的工具**  
**示例 1：创建一个准备接受密钥和索引定义的空 TableSchema 对象，用于创建新的 Amazon DynamoDB 表。返回的对象可以通过管道传输到 Add-DDBKey Schema、Add-Schema 和 New-DDBIndex cmdlet 中，也可以使用每个 DDBTable cmdlet 上的-Schema 参数传递给它们。**  

```
New-DDBTableSchema
```
**输出**：  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{}                                          {}                                          {}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) 中的 “[新建DDBTable架构](https://docs.aws.amazon.com/powershell/v5/reference)”。

### `Remove-DDBItem`
<a name="dynamodb_DeleteItem_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DDBItem`。

**适用于 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 参考 (V* 5) [DeleteItem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-DDBTable`
<a name="dynamodb_DeleteTable_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-DDBTable`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的表。在操作继续之前，系统会提示您进行确认。**  

```
Remove-DDBTable -TableName "myTable"
```
**示例 2：删除指定的表。在操作继续之前，系统不会提示您进行确认。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-DDBBatchItem`
<a name="dynamodb_BatchWriteItem_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-DDBBatchItem`。

**适用于 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 参考 (V* 5) [BatchWriteItem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-DDBItem`
<a name="dynamodb_PutItem_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-DDBItem`。

**适用于 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 参考 (V* 5) [PutItem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-DDBItem`
<a name="dynamodb_UpdateItem_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-DDBItem`。

**适用于 PowerShell V5 的工具**  
**示例 1：使用分区 SongTitle 键和排序键 Artist 将 DynamoDB 项目上的流派属性设置为 “说唱”。**  

```
$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 参考 (V* 5) [UpdateItem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-DDBTable`
<a name="dynamodb_UpdateTable_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-DDBTable`。

**适用于 PowerShell V5 的工具**  
**示例 1：更新给定表的预置吞吐量。**  

```
Update-DDBTable -TableName "myTable" -ReadCapacity 10 -WriteCapacity 5
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的亚马逊 EC2 示例
<a name="powershell_ec2_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon EC2 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-EC2CapacityReservation`
<a name="ec2_CreateCapacityReservation_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-EC2CapacityReservation`。

**适用于 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 参考 (V* 5) [CreateCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-EC2InternetGateway`
<a name="ec2_AttachInternetGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-EC2InternetGateway`。

**适用于 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 参考 (V* 5) [AttachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-EC2NetworkInterface`
<a name="ec2_AttachNetworkInterface_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-EC2NetworkInterface`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的网络接口连接到指定的实例。**  

```
Add-EC2NetworkInterface -NetworkInterfaceId eni-12345678 -InstanceId i-1a2b3c4d -DeviceIndex 1
```
**输出**：  

```
eni-attach-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-EC2Volume`
<a name="ec2_AttachVolume_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-EC2Volume`。

**适用于 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 参考 (V* 5) [AttachVolume](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-EC2VpnGateway`
<a name="ec2_AttachVpnGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-EC2VpnGateway`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的虚拟专用网关连接到指定的 VPC。**  

```
Add-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
**输出**：  

```
State        VpcId
-----        -----
attaching    vpc-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Approve-EC2VpcPeeringConnection`
<a name="ec2_AcceptVpcPeeringConnection_powershell_topic"></a>

以下代码示例演示了如何使用 `Approve-EC2VpcPeeringConnection`。

**适用于 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 参考 (V* 5) [AcceptVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Confirm-EC2ProductInstance`
<a name="ec2_ConfirmProductInstance_powershell_topic"></a>

以下代码示例演示了如何使用 `Confirm-EC2ProductInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例确定指定的产品代码是否与指定的实例相关联。**  

```
Confirm-EC2ProductInstance -ProductCode 774F4FF8 -InstanceId i-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ConfirmProductInstance](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Copy-EC2Image`
<a name="ec2_CopyImage_powershell_topic"></a>

以下代码示例演示了如何使用 `Copy-EC2Image`。

**适用于 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 参考 (V* 5) [CopyImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Copy-EC2Snapshot`
<a name="ec2_CopySnapshot_powershell_topic"></a>

以下代码示例演示了如何使用 `Copy-EC2Snapshot`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的快照从欧洲地区（爱尔兰）区域复制到美国西部（俄勒冈州）区域。**  

```
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678 -Region us-west-2
```
**示例 2：如果您设置了默认区域并省略了 Region 参数，则默认目标区域为默认区域。**  

```
Set-DefaultAWSRegion us-west-2
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CopySnapshot](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Deny-EC2VpcPeeringConnection`
<a name="ec2_RejectVpcPeeringConnection_powershell_topic"></a>

以下代码示例演示了如何使用 `Deny-EC2VpcPeeringConnection`。

**适用于 PowerShell V5 的工具**  
**示例 1：上面的示例拒绝了请求编号为 pcx-01a2b3ce45fe67eb8 的 VpcPeering 请求**  

```
Deny-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-01a2b3ce45fe67eb8
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RejectVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-EC2VgwRoutePropagation`
<a name="ec2_DisableVgwRoutePropagation_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-EC2VgwRoutePropagation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁止 VGW 自动将路由传播到指定的路由表。**  

```
Disable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-EC2VpcClassicLink`
<a name="ec2_DisableVpcClassicLink_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-EC2VpcClassicLink`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁用 vpc-01e23c4a5d6d EC2 VpcClassicLink b78e9。它返回 True 或 False**  

```
Disable-EC2VpcClassicLink -VpcId vpc-01e23c4a5d6db78e9
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DisableVpcClassicLinkDnsSupport_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-EC2VpcClassicLinkDnsSupport`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁用了对 vpc-0b12d3456a7e ClassicLink 8910d 的 DNS 支持**  

```
Disable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Dismount-EC2InternetGateway`
<a name="ec2_DetachInternetGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `Dismount-EC2InternetGateway`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的互联网网关与指定的 VPC 分离。**  

```
Dismount-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DetachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Dismount-EC2NetworkInterface`
<a name="ec2_DetachNetworkInterface_powershell_topic"></a>

以下代码示例演示了如何使用 `Dismount-EC2NetworkInterface`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例移除网络接口和实例之间的指定连接。**  

```
Dismount-EC2NetworkInterface -AttachmentId eni-attach-1a2b3c4d -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DetachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Dismount-EC2Volume`
<a name="ec2_DetachVolume_powershell_topic"></a>

以下代码示例演示了如何使用 `Dismount-EC2Volume`。

**适用于 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 参考 (V* 5) [DetachVolume](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Dismount-EC2VpnGateway`
<a name="ec2_DetachVpnGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `Dismount-EC2VpnGateway`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的虚拟专用网关与指定的 VPC 分离。**  

```
Dismount-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DetachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2CapacityReservation`
<a name="ec2_ModifyCapacityReservation_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2CapacityReservation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例通过将实例计数更改为 1 来修改 CapacityReservationId cr-0c1f2345db6f7cdba**  

```
Edit-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba -InstanceCount 1
```
**输出**：  

```
True
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2Host`
<a name="ec2_ModifyHosts_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2Host`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将专用主机的 AutoPlacement 设置修改为关闭 h-01e23f4cd567890f3**  

```
Edit-EC2Host -HostId h-03e09f8cd681609f3 -AutoPlacement off
```
**输出**：  

```
Successful            Unsuccessful
----------            ------------
{h-01e23f4cd567890f3} {}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyHosts](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2IdFormat`
<a name="ec2_ModifyIdFormat_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2IdFormat`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为指定的资源类型启用较长的 ID 格式。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $true
```
**示例 2：此示例为指定的资源类型禁用较长的 ID 格式。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2ImageAttribute`
<a name="ec2_ModifyImageAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2ImageAttribute`。

**适用于 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 参考 (V* 5) [ModifyImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2InstanceAttribute`
<a name="ec2_ModifyInstanceAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2InstanceAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例修改指定实例的实例类型。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceType m3.medium
```
**示例 2：此示例通过将 “simple” 指定为单根虚拟化 (SR-IOV) 网络支持参数的值，为指定实例启用增强联网，方法是将 “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：此示例启用了对指定实例的 source/destination 检查。对于要执行 NAT 的 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 参考 (V* 5) [ModifyInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2InstanceCreditSpecification`
<a name="ec2_ModifyInstanceCreditSpecification_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2InstanceCreditSpecification`。

**适用于 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 参考 (V* 5) [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2NetworkInterfaceAttribute`
<a name="ec2_ModifyNetworkInterfaceAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2NetworkInterfaceAttribute`。

**适用于 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：此示例禁用对指定网络接口的 source/destination 检查。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2ReservedInstance`
<a name="ec2_ModifyReservedInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2ReservedInstance`。

**适用于 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 参考 (V* 5) [ModifyReservedInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2SnapshotAttribute`
<a name="ec2_ModifySnapshotAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2SnapshotAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例通过设置指定快照的 CreateVolumePermission 属性将其公开。**  

```
Edit-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission -OperationType Add -GroupName all
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifySnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2SpotFleetRequest`
<a name="ec2_ModifySpotFleetRequest_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2SpotFleetRequest`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新指定竞价型实例集请求的目标容量。**  

```
Edit-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TargetCapacity 10
```
**输出**：  

```
True
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifySpotFleetRequest](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2SubnetAttribute`
<a name="ec2_ModifySubnetAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2SubnetAttribute`。

**适用于 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 参考 (V* 5) [ModifySubnetAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2VolumeAttribute`
<a name="ec2_ModifyVolumeAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2VolumeAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例修改了指定卷的指定属性。 I/O 由于数据可能不一致，该卷的操作将在暂停后自动恢复。**  

```
Edit-EC2VolumeAttribute -VolumeId vol-12345678 -AutoEnableIO $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-EC2VpcAttribute`
<a name="ec2_ModifyVpcAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EC2VpcAttribute`。

**适用于 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 参考 (V* 5) [ModifyVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-EC2VgwRoutePropagation`
<a name="ec2_EnableVgwRoutePropagation_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-EC2VgwRoutePropagation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例支持指定的 VGW 自动将路由传播到指定的路由表。**  

```
Enable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-EC2VolumeIO`
<a name="ec2_EnableVolumeIo_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-EC2VolumeIO`。

**适用于 PowerShell V5 的工具**  
**示例 1：如果禁用了 I/O 操作，则此示例将启用对指定卷的 I/O 操作。**  

```
Enable-EC2VolumeIO -VolumeId vol-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableVolumeIo](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-EC2VpcClassicLink`
<a name="ec2_EnableVpcClassicLink_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-EC2VpcClassicLink`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用 VPC vpc-0123456b789b0d12f ClassicLink**  

```
Enable-EC2VpcClassicLink -VpcId vpc-0123456b789b0d12f
```
**输出**：  

```
True
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_EnableVpcClassicLinkDnsSupport_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-EC2VpcClassicLinkDnsSupport`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用 vpc-0b12d3456a7e8910d 支持 DNS 主机名解析 ClassicLink**  

```
Enable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2AccountAttribute`
<a name="ec2_DescribeAccountAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2AccountAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述了您是可以在该区域的 EC2-Classic 和 EC2-VPC 中启动实例，还是只能启动到-VPC 中 EC2。**  

```
(Get-EC2AccountAttribute -AttributeName supported-platforms).AttributeValues
```
**输出**：  

```
AttributeValue
--------------
EC2
VPC
```
**示例 2：此示例描述您的默认 VPC，或者如果您在该区域没有默认 VPC，则为“无”。**  

```
(Get-EC2AccountAttribute -AttributeName default-vpc).AttributeValues
```
**输出**：  

```
AttributeValue
--------------
vpc-12345678
```
**示例 3：此示例描述您可以运行的最大按需型实例数。**  

```
(Get-EC2AccountAttribute -AttributeName max-instances).AttributeValues
```
**输出**：  

```
AttributeValue
--------------
20
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAccountAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Address`
<a name="ec2_DescribeAddresses_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Address`。

**适用于 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：此示例检索所有 Elast IPs ic 及其分配 ID、关联 ID 和实例 ID**  

```
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” 的 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 参考 (V* 5) [DescribeAddresses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2AvailabilityZone`
<a name="ec2_DescribeAvailabilityZones_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2AvailabilityZone`。

**适用于 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 参考 (V* 5) [DescribeAvailabilityZones](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2BundleTask`
<a name="ec2_DescribeBundleTasks_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2BundleTask`。

**适用于 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 参考 (V* 5) [DescribeBundleTasks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2CapacityReservation`
<a name="ec2_DescribeCapacityReservations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2CapacityReservation`。

**适用于 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 参考 (V* 5) [DescribeCapacityReservations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2ConsoleOutput`
<a name="ec2_GetConsoleOutput_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2ConsoleOutput`。

**适用于 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 参考 (V* 5) [GetConsoleOutput](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2CustomerGateway`
<a name="ec2_DescribeCustomerGateways_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2CustomerGateway`。

**适用于 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 参考 (V* 5) [DescribeCustomerGateways](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2DhcpOption`
<a name="ec2_DescribeDhcpOptions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2DhcpOption`。

**适用于 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 参考 (V* 5) [DescribeDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2FlowLog`
<a name="ec2_DescribeFlowLogs_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2FlowLog`。

**适用于 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 参考 (V* 5) [DescribeFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Host`
<a name="ec2_DescribeHosts_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Host`。

**适用于 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-01e23f4c AvailableInstanceCapacity d567899f1**  

```
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 参考 (V* 5) [DescribeHosts](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2HostReservationOffering`
<a name="ec2_DescribeHostReservationOfferings_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2HostReservationOffering`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述了可为给定过滤器 “实例系列” 购买的专用主机预留 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 参考 (V* 5) [DescribeHostReservationOfferings](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2HostReservationPurchasePreview`
<a name="ec2_GetHostReservationPurchasePreview_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2HostReservationPurchasePreview`。

**适用于 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 参考 (V* 5) [GetHostReservationPurchasePreview](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2IdFormat`
<a name="ec2_DescribeIdFormat_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2IdFormat`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定资源类型的 ID 格式。**  

```
Get-EC2IdFormat -Resource instance
```
**输出**：  

```
Resource       UseLongIds
--------       ----------
instance       False
```
**示例 2：此示例描述了所有支持更长时间的资源类型的 ID 格式 IDs。**  

```
Get-EC2IdFormat
```
**输出**：  

```
Resource       UseLongIds
--------       ----------
reservation    False
instance       False
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2IdentityIdFormat`
<a name="ec2_DescribeIdentityIdFormat_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2IdentityIdFormat`。

**适用于 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 参考 (V* 5) [DescribeIdentityIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Image`
<a name="ec2_DescribeImages_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Image`。

**适用于 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：此示例描述 AMIs 了您拥有的。**  

```
Get-EC2Image -owner self
```
**示例 3：此示例描述了运行微软 Windows Server 的公众 AMIs 。**  

```
Get-EC2Image -Filter @{ Name="platform"; Values="windows" }
```
**示例 4：此示例描述了 “us-west-2” 区域的所有公众 AMIs 。**  

```
Get-EC2Image -Region us-west-2
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeImages](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2ImageAttribute`
<a name="ec2_DescribeImageAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2ImageAttribute`。

**适用于 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 参考 (V* 5) [DescribeImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2ImportImageTask`
<a name="ec2_DescribeImportImageTasks_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2ImportImageTask`。

**适用于 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 参考 (V* 5) [DescribeImportImageTasks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2ImportSnapshotTask`
<a name="ec2_DescribeImportSnapshotTasks_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2ImportSnapshotTask`。

**适用于 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 参考 (V* 5) [DescribeImportSnapshotTasks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Instance`
<a name="ec2_DescribeInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Instance`。

**适用于 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：此示例验证了在不实际获取 EC2 实例的情况下使用 DryRun 参数获取实例的权限。注：这在操作成功时会引发异常，这是预期行为。**  

```
Get-EC2Tag -DryRun $true
```
**输出**：  

```
Get-EC2Instance: Request would have succeeded, but DryRun flag is set.
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2InstanceAttribute`
<a name="ec2_DescribeInstanceAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2InstanceAttribute`。

**适用于 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：此示例描述了指定实例instanceInitiatedShutdown的 “行为” 属性。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
**输出**：  

```
InstanceInitiatedShutdownBehavior : stop
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2InstanceMetadata`
<a name="ec2_Get-EC2InstanceMetadata_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2InstanceMetadata`。

**适用于 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：返回用于启动实例的亚马逊机器映像（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 参考 (V* 5) [Get-EC2InstanceMetadata](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2InstanceStatus`
<a name="ec2_DescribeInstanceStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2InstanceStatus`。

**适用于 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 参考 (V* 5) [DescribeInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2InternetGateway`
<a name="ec2_DescribeInternetGateways_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2InternetGateway`。

**适用于 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 参考 (V* 5) [DescribeInternetGateways](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2KeyPair`
<a name="ec2_DescribeKeyPairs_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2KeyPair`。

**适用于 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 参考 (V* 5) [DescribeKeyPairs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2NetworkAcl`
<a name="ec2_DescribeNetworkAcls_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2NetworkAcl`。

**适用于 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：此示例描述了您的所有网络 ACLs。**  

```
Get-EC2NetworkAcl
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeNetworkAcls](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2NetworkInterface`
<a name="ec2_DescribeNetworkInterfaces_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2NetworkInterface`。

**适用于 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 参考 (V* 5) [DescribeNetworkInterfaces](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2NetworkInterfaceAttribute`
<a name="ec2_DescribeNetworkInterfaceAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2NetworkInterfaceAttribute`。

**适用于 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 参考 (V* 5) [DescribeNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2PasswordData`
<a name="ec2_GetPasswordData_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2PasswordData`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例解密亚马逊为指定 Windows 实例的管理员账户 EC2 分配的密码。当指定了 pem 文件时，将自动假定 -Decrypt 开关的设置。**  

```
Get-EC2PasswordData -InstanceId i-12345678 -PemFile C:\path\my-key-pair.pem
```
**输出**：  

```
mYZ(PA9?C)Q
```
**示例 2：（ PowerShell 仅限 Windows）检查实例以确定用于启动实例的密钥对的名称，然后尝试在 Visual Studio T AWS oolkit 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 参考 (V* 5) [GetPasswordData](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2PlacementGroup`
<a name="ec2_DescribePlacementGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2PlacementGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定的置放群组。**  

```
Get-EC2PlacementGroup -GroupName my-placement-group
```
**输出**：  

```
GroupName             State        Strategy
---------             -----        --------
my-placement-group    available    cluster
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribePlacementGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2PrefixList`
<a name="ec2_DescribePrefixLists_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2PrefixList`。

**适用于 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 参考 (V* 5) [DescribePrefixLists](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Region`
<a name="ec2_DescribeRegions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Region`。

**适用于 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 参考 (V* 5) [DescribeRegions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2RouteTable`
<a name="ec2_DescribeRouteTables_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2RouteTable`。

**适用于 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 参考 (V* 5) [DescribeRouteTables](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2ScheduledInstance`
<a name="ec2_DescribeScheduledInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2ScheduledInstance`。

**适用于 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 参考 (V* 5) [DescribeScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2ScheduledInstanceAvailability`
<a name="ec2_DescribeScheduledInstanceAvailability_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2ScheduledInstanceAvailability`。

**适用于 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 参考 (V* 5) [DescribeScheduledInstanceAvailability](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SecurityGroup`
<a name="ec2_DescribeSecurityGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SecurityGroup`。

**适用于 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 参考 (V* 5) [DescribeSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Snapshot`
<a name="ec2_DescribeSnapshots_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Snapshot`。

**适用于 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” 的快照。**  

```
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 参考 (V* 5) [DescribeSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SnapshotAttribute`
<a name="ec2_DescribeSnapshotAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SnapshotAttribute`。

**适用于 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 参考 (V* 5) [DescribeSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SpotDatafeedSubscription`
<a name="ec2_DescribeSpotDatafeedSubscription_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SpotDatafeedSubscription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述竞价型实例数据源。**  

```
Get-EC2SpotDatafeedSubscription
```
**输出**：  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SpotFleetInstance`
<a name="ec2_DescribeSpotFleetInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SpotFleetInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述与指定竞价型实例集请求关联的实例。**  

```
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 参考 (V* 5) [DescribeSpotFleetInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SpotFleetRequest`
<a name="ec2_DescribeSpotFleetRequests_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SpotFleetRequest`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定的竞价型实例集请求。**  

```
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：此示例描述所有竞价型实例集请求。**  

```
Get-EC2SpotFleetRequest
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SpotFleetRequestHistory`
<a name="ec2_DescribeSpotFleetRequestHistory_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SpotFleetRequestHistory`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定的竞价型实例集请求的历史记录。**  

```
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 参考 (V* 5) [DescribeSpotFleetRequestHistory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SpotInstanceRequest`
<a name="ec2_DescribeSpotInstanceRequests_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SpotInstanceRequest`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定的竞价型实例请求。**  

```
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：此示例描述所有竞价型实例请求。**  

```
Get-EC2SpotInstanceRequest
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2SpotPriceHistory`
<a name="ec2_DescribeSpotPriceHistory_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2SpotPriceHistory`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定实例类型和可用区的竞价价格历史记录中的最后 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 参考 (V* 5) [DescribeSpotPriceHistory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Subnet`
<a name="ec2_DescribeSubnets_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Subnet`。

**适用于 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 参考 (V* 5) [DescribeSubnets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Tag`
<a name="ec2_DescribeTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Tag`。

**适用于 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：此示例获取所有带有 “auto-delete” 标签且值为 “无” 的资源，并在下一个管道中进行进一步筛选以仅解析 “实例” 资源类型，最终为每个实例资源创建 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 参考 (V* 5) [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Volume`
<a name="ec2_DescribeVolumes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Volume`。

**适用于 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：此示例描述状态为“可用”的 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 参考 (V* 5) [DescribeVolumes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VolumeAttribute`
<a name="ec2_DescribeVolumeAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VolumeAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定卷的指定属性。**  

```
Get-EC2VolumeAttribute -VolumeId vol-12345678 -Attribute AutoEnableIO
```
**输出**：  

```
AutoEnableIO    ProductCodes    VolumeId
------------    ------------    --------
False           {}              vol-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VolumeStatus`
<a name="ec2_DescribeVolumeStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VolumeStatus`。

**适用于 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 参考 (V* 5) [DescribeVolumeStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2Vpc`
<a name="ec2_DescribeVpcs_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2Vpc`。

**适用于 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：此示例描述了 VPCs 与指定过滤器匹配的（即，具有与值 “10.0.0.0/16” 匹配且处于 “可用” 状态的 CIDR）。**  

```
Get-EC2Vpc -Filter @{Name="cidr"; Values="10.0.0.0/16"},@{Name="state";Values="available"}
```
**示例 4: 此示例描述了您的所有内容 VPCs.**  

```
Get-EC2Vpc
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeVpcs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VpcAttribute`
<a name="ec2_DescribeVpcAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VpcAttribute`。

**适用于 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 参考 (V* 5) [DescribeVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VpcClassicLink`
<a name="ec2_DescribeVpcClassicLink_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VpcClassicLink`。

**适用于 PowerShell V5 的工具**  
**示例 1：上面的示例返回 VPCs 了该区域的所有及其 ClassicLinkEnabled 状态**  

```
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 参考 (V* 5) [DescribeVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DescribeVpcClassicLinkDnsSupport_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VpcClassicLinkDnsSupport`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述了 eu-west-1 区域 VPCs 的 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 参考 (V* 5) [DescribeVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VpcEndpoint`
<a name="ec2_DescribeVpcEndpoints_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VpcEndpoint`。

**适用于 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 参考 (V* 5) [DescribeVpcEndpoints](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VpcEndpointService`
<a name="ec2_DescribeVpcEndpointServices_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VpcEndpointService`。

**适用于 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 终端节点服务并返回 ServiceNames 匹配的 “ssm”**  

```
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 参考 (V* 5) [DescribeVpcEndpointServices](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VpnConnection`
<a name="ec2_DescribeVpnConnections_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VpnConnection`。

**适用于 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 参考 (V* 5) [DescribeVpnConnections](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EC2VpnGateway`
<a name="ec2_DescribeVpnGateways_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EC2VpnGateway`。

**适用于 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 参考 (V* 5) [DescribeVpnGateways](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Grant-EC2SecurityGroupEgress`
<a name="ec2_AuthorizeSecurityGroupEgress_powershell_topic"></a>

以下代码示例演示了如何使用 `Grant-EC2SecurityGroupEgress`。

**适用于 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 参考 (V* 5) [AuthorizeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Grant-EC2SecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_powershell_topic"></a>

以下代码示例演示了如何使用 `Grant-EC2SecurityGroupIngress`。

**适用于 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：此示例授予 TCP 端口 8081 从指定的源安全组（sg-1a2b3c4d）到指定的安全组（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 添加到 TCP 端口 22 流量的安全组 sg-1234abcd 的入口规则中，并附有描述。**  

```
$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 参考 (V* 5) [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Import-EC2Image`
<a name="ec2_ImportImage_powershell_topic"></a>

以下代码示例演示了如何使用 `Import-EC2Image`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用等性令牌将单磁盘虚拟机映像从指定的 Amazon S3 存储桶导入到 EC2 Amazon。该示例要求存在默认名称为 “vmimport” 的虚拟机导入服务角色，其策略允许亚马逊 EC2 访问指定的存储桶，如虚拟机导入先决条件主题中所述。要使用自定义角色，请使用 `-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 参考 (V* 5) [ImportImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Import-EC2KeyPair`
<a name="ec2_ImportKeyPair_powershell_topic"></a>

以下代码示例演示了如何使用 `Import-EC2KeyPair`。

**适用于 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 参考 (V* 5) [ImportKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Import-EC2Snapshot`
<a name="ec2_ImportSnapshot_powershell_topic"></a>

以下代码示例演示了如何使用 `Import-EC2Snapshot`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将格式为“VMDK”的虚拟机磁盘映像导入到 Amazon EBS 快照中。该示例需要一个默认名称为 “vmimport” 的虚拟机导入服务角色，其策略允许亚马逊 EC2 访问指定的存储桶，如 http://docs.aws.amazon 中的`VM Import Prequisites`主题所述。 com/AWSEC2/latest/WindowsGuide/VMImportPrerequisites.html。要使用自定义角色，请使用 `-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 参考 (V* 5) [ImportSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Move-EC2AddressToVpc`
<a name="ec2_MoveAddressToVpc_powershell_topic"></a>

以下代码示例演示了如何使用 `Move-EC2AddressToVpc`。

**适用于 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 参考 (V* 5) [MoveAddressToVpc](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Address`
<a name="ec2_AllocateAddress_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Address`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例分配一个弹性 IP 地址，供 VPC 中的实例使用。**  

```
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 参考 (V* 5) [AllocateAddress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2CustomerGateway`
<a name="ec2_CreateCustomerGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2CustomerGateway`。

**适用于 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 参考 (V* 5) [CreateCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2DhcpOption`
<a name="ec2_CreateDhcpOptions_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2DhcpOption`。

**适用于 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 参考 (V* 5) [CreateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2FlowLog`
<a name="ec2_CreateFlowLogs_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2FlowLog`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用 “管理员” 角色的权限为所有 “拒绝” EC2 流量创建子网 subnet-1d234567 到 cloud-watch-log名为 “subnet1-log” 的流日志**  

```
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 参考 (V* 5) [CreateFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Host`
<a name="ec2_AllocateHosts_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Host`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例向您的账户分配给定实例类型和可用区的专属主机**  

```
New-EC2Host -AutoPlacement on -AvailabilityZone eu-west-1b -InstanceType m4.xlarge -Quantity 1
```
**输出**：  

```
h-01e23f4cd567890f3
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AllocateHosts](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2HostReservation`
<a name="ec2_PurchaseHostReservation_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2HostReservation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例购买可提供 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 参考 (V* 5) [PurchaseHostReservation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Image`
<a name="ec2_CreateImage_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Image`。

**适用于 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 参考 (V* 5) [CreateImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Instance`
<a name="ec2_RunInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Instance`。

**适用于 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 中的一个 AMIs，请使用 Get-I SSMLatest EC2 mage 获取其 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：此请求启动两个实例，并将键为 webserver 和值为 production 的标签应用于实例。该请求还向创建的卷（此示例中为每个实例的根卷）应用键为 cost-center 且值为 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 参考 (V* 5) [RunInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2InstanceExportTask`
<a name="ec2_CreateInstanceExportTask_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2InstanceExportTask`。

**适用于 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 参考 (V* 5) [CreateInstanceExportTask](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2InternetGateway`
<a name="ec2_CreateInternetGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2InternetGateway`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建互联网网关。**  

```
New-EC2InternetGateway
```
**输出**：  

```
Attachments    InternetGatewayId    Tags
-----------    -----------------    ----
{}             igw-1a2b3c4d         {}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2KeyPair`
<a name="ec2_CreateKeyPair_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2KeyPair`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建一个密钥对，并在具有指定名称的文件中捕获经过 PEM 编码的 RSA 私有密钥。使用时 PowerShell，必须将编码设置为 ascii 才能生成有效的密钥。有关更多信息，请参阅《 AWS 命令行界面用户指南》中的创建、显示和删除亚马逊 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 参考 (V* 5) [CreateKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2NetworkAcl`
<a name="ec2_CreateNetworkAcl_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2NetworkAcl`。

**适用于 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 参考 (V* 5) [CreateNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2NetworkAclEntry`
<a name="ec2_CreateNetworkAclEntry_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2NetworkAclEntry`。

**适用于 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 参考 (V* 5) [CreateNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2NetworkInterface`
<a name="ec2_CreateNetworkInterface_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2NetworkInterface`。

**适用于 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 参考 (V* 5) [CreateNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2PlacementGroup`
<a name="ec2_CreatePlacementGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2PlacementGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例命令使用指定的名称创建置放群组。**  

```
New-EC2PlacementGroup -GroupName my-placement-group -Strategy cluster
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreatePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Route`
<a name="ec2_CreateRoute_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Route`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为指定的路由表创建指定的路由。该路由匹配所有流量，并将其路由到指定的互联网网关。**  

```
New-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0 -GatewayId igw-1a2b3c4d
```
**输出**：  

```
True
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateRoute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2RouteTable`
<a name="ec2_CreateRouteTable_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2RouteTable`。

**适用于 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 参考 (V* 5) [CreateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2ScheduledInstance`
<a name="ec2_RunScheduledInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2ScheduledInstance`。

**适用于 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 参考 (V* 5) [RunScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2ScheduledInstancePurchase`
<a name="ec2_PurchaseScheduledInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2ScheduledInstancePurchase`。

**适用于 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 参考 (V* 5) [PurchaseScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2SecurityGroup`
<a name="ec2_CreateSecurityGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2SecurityGroup`。

**适用于 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 参考 (V* 5) [CreateSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Snapshot`
<a name="ec2_CreateSnapshot_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Snapshot`。

**适用于 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 参考 (V* 5) [CreateSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2SpotDatafeedSubscription`
<a name="ec2_CreateSpotDatafeedSubscription_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2SpotDatafeedSubscription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建竞价型实例数据源。**  

```
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 参考 (V* 5) [CreateSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Subnet`
<a name="ec2_CreateSubnet_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Subnet`。

**适用于 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 参考 (V* 5) [CreateSubnet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Tag`
<a name="ec2_CreateTags_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Tag`。

**适用于 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 = 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 参考 (V* 5) [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Volume`
<a name="ec2_CreateVolume_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Volume`。

**适用于 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：此示例请求创建一个卷，并应用键为 stack 且值为 production 的标签。**  

```
$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 参考 (V* 5) [CreateVolume](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2Vpc`
<a name="ec2_CreateVpc_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2Vpc`。

**适用于 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 参考 (V* 5) [CreateVpc](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2VpcEndpoint`
<a name="ec2_CreateVpcEndpoint_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2VpcEndpoint`。

**适用于 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 参考 (V* 5) [CreateVpcEndpoint](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2VpnConnection`
<a name="ec2_CreateVpnConnection_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2VpnConnection`。

**适用于 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 参考 (V* 5) [CreateVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2VpnConnectionRoute`
<a name="ec2_CreateVpnConnectionRoute_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2VpnConnectionRoute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为指定的 VPN 连接创建指定的静态路由。**  

```
New-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EC2VpnGateway`
<a name="ec2_CreateVpnGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EC2VpnGateway`。

**适用于 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 参考 (V* 5) [CreateVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-EC2Address`
<a name="ec2_AssociateAddress_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-EC2Address`。

**适用于 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 参考 (V* 5) [AssociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-EC2DhcpOption`
<a name="ec2_AssociateDhcpOptions_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-EC2DhcpOption`。

**适用于 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 参考 (V* 5) [AssociateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-EC2Image`
<a name="ec2_RegisterImage_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-EC2Image`。

**适用于 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 参考 (V* 5) [RegisterImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-EC2PrivateIpAddress`
<a name="ec2_AssignPrivateIpAddresses_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-EC2PrivateIpAddress`。

**适用于 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 参考 (V* 5) [AssignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-EC2RouteTable`
<a name="ec2_AssociateRouteTable_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-EC2RouteTable`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的路由表与指定的子网相关联。**  

```
Register-EC2RouteTable -RouteTableId rtb-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**输出**：  

```
rtbassoc-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AssociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Address`
<a name="ec2_ReleaseAddress_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Address`。

**适用于 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 参考 (V* 5) [ReleaseAddress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2CapacityReservation`
<a name="ec2_CancelCapacityReservation_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2CapacityReservation`。

**适用于 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 参考 (V* 5) [CancelCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2CustomerGateway`
<a name="ec2_DeleteCustomerGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2CustomerGateway`。

**适用于 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 参考 (V* 5) [DeleteCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2DhcpOption`
<a name="ec2_DeleteDhcpOptions_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2DhcpOption`。

**适用于 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 参考 (V* 5) [DeleteDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2FlowLog`
<a name="ec2_DeleteFlowLogs_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2FlowLog`。

**适用于 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 参考 (V* 5) [DeleteFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Host`
<a name="ec2_ReleaseHosts_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Host`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例释放给定的主机 ID 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 参考 (V* 5) [ReleaseHosts](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Instance`
<a name="ec2_TerminateInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Instance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例终止指定的实例（该实例可能正在运行或处于“已停止”状态）。在继续操作之前，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 参考 (V* 5) [TerminateInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2InternetGateway`
<a name="ec2_DeleteInternetGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2InternetGateway`。

**适用于 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 参考 (V* 5) [DeleteInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2KeyPair`
<a name="ec2_DeleteKeyPair_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2KeyPair`。

**适用于 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 参考 (V* 5) [DeleteKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2NetworkAcl`
<a name="ec2_DeleteNetworkAcl_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2NetworkAcl`。

**适用于 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 参考 (V* 5) [DeleteNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2NetworkAclEntry`
<a name="ec2_DeleteNetworkAclEntry_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2NetworkAclEntry`。

**适用于 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 参考 (V* 5) [DeleteNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2NetworkInterface`
<a name="ec2_DeleteNetworkInterface_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2NetworkInterface`。

**适用于 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 参考 (V* 5) [DeleteNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2PlacementGroup`
<a name="ec2_DeletePlacementGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2PlacementGroup`。

**适用于 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 参考 (V* 5) [DeletePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Route`
<a name="ec2_DeleteRoute_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Route`。

**适用于 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 参考 (V* 5) [DeleteRoute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2RouteTable`
<a name="ec2_DeleteRouteTable_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2RouteTable`。

**适用于 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 参考 (V* 5) [DeleteRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2SecurityGroup`
<a name="ec2_DeleteSecurityGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2SecurityGroup`。

**适用于 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 参考 (V* 5) [DeleteSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Snapshot`
<a name="ec2_DeleteSnapshot_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Snapshot`。

**适用于 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 参考 (V* 5) [DeleteSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2SpotDatafeedSubscription`
<a name="ec2_DeleteSpotDatafeedSubscription_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2SpotDatafeedSubscription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除竞价型实例数据源。除非您还指定了 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 参考 (V* 5) [DeleteSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Subnet`
<a name="ec2_DeleteSubnet_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Subnet`。

**适用于 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 参考 (V* 5) [DeleteSubnet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Tag`
<a name="ec2_DeleteTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Tag`。

**适用于 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 参考 (V* 5) [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Volume`
<a name="ec2_DeleteVolume_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Volume`。

**适用于 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 参考 (V* 5) [DeleteVolume](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2Vpc`
<a name="ec2_DeleteVpc_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2Vpc`。

**适用于 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 参考 (V* 5) [DeleteVpc](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2VpnConnection`
<a name="ec2_DeleteVpnConnection_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2VpnConnection`。

**适用于 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 参考 (V* 5) [DeleteVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2VpnConnectionRoute`
<a name="ec2_DeleteVpnConnectionRoute_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2VpnConnectionRoute`。

**适用于 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 参考 (V* 5) [DeleteVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EC2VpnGateway`
<a name="ec2_DeleteVpnGateway_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EC2VpnGateway`。

**适用于 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 参考 (V* 5) [DeleteVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Request-EC2SpotFleet`
<a name="ec2_RequestSpotFleet_powershell_topic"></a>

以下代码示例演示了如何使用 `Request-EC2SpotFleet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在价格最低的可用区中为指定的实例类型创建竞价型实例集请求。如果您的账户仅支持 EC2-VPC，则竞价型队列会在具有默认子网的价格最低的可用区启动实例。如果您的账户支持 EC2-Classic，则竞价型队列会在价格最低的可用区中启动 EC2-Classic 中的实例。请注意，您支付的价格不会超过请求的指定竞价价格。**  

```
$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 参考 (V* 5) [RequestSpotFleet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Request-EC2SpotInstance`
<a name="ec2_RequestSpotInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Request-EC2SpotInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在指定的子网中请求一次性竞价型实例。请注意，必须为包含指定子网的 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 参考 (V* 5) [RequestSpotInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Reset-EC2ImageAttribute`
<a name="ec2_ResetImageAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Reset-EC2ImageAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将“launchPermission”属性重置为其默认值。默认情况下， AMIs 是私有的。**  

```
Reset-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResetImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Reset-EC2InstanceAttribute`
<a name="ec2_ResetInstanceAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Reset-EC2InstanceAttribute`。

**适用于 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：此示例重置指定实例的 instanceInitiatedShutdown “行为” 属性。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResetInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Reset-EC2NetworkInterfaceAttribute`
<a name="ec2_ResetNetworkInterfaceAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Reset-EC2NetworkInterfaceAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例重置对指定网络接口的 source/destination 检查。**  

```
Reset-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResetNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Reset-EC2SnapshotAttribute`
<a name="ec2_ResetSnapshotAttribute_powershell_topic"></a>

以下代码示例演示了如何使用 `Reset-EC2SnapshotAttribute`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例重置指定快照的指定属性。**  

```
Reset-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResetSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Restart-EC2Instance`
<a name="ec2_RebootInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Restart-EC2Instance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例重启指定的实例。**  

```
Restart-EC2Instance -InstanceId i-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RebootInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Revoke-EC2SecurityGroupEgress`
<a name="ec2_RevokeSecurityGroupEgress_powershell_topic"></a>

以下代码示例演示了如何使用 `Revoke-EC2SecurityGroupEgress`。

**适用于 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 参考 (V* 5) [RevokeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Revoke-EC2SecurityGroupIngress`
<a name="ec2_RevokeSecurityGroupIngress_powershell_topic"></a>

以下代码示例演示了如何使用 `Revoke-EC2SecurityGroupIngress`。

**适用于 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 参考 (V* 5) [RevokeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Send-EC2InstanceStatus`
<a name="ec2_ReportInstanceStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Send-EC2InstanceStatus`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例报告指定实例的状态反馈。**  

```
Send-EC2InstanceStatus -Instance i-12345678 -Status impaired -ReasonCode unresponsive
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ReportInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-EC2NetworkAclAssociation`
<a name="ec2_ReplaceNetworkAclAssociation_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-EC2NetworkAclAssociation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的网络 ACL 与指定网络 ACL 关联的子网相关联。**  

```
Set-EC2NetworkAclAssociation -NetworkAclId acl-12345678 -AssociationId aclassoc-1a2b3c4d
```
**输出**：  

```
aclassoc-87654321
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ReplaceNetworkAclAssociation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-EC2NetworkAclEntry`
<a name="ec2_ReplaceNetworkAclEntry_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-EC2NetworkAclEntry`。

**适用于 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 参考 (V* 5) [ReplaceNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-EC2Route`
<a name="ec2_ReplaceRoute_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-EC2Route`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例替换指定路由表的指定路由。新路由将指定的流量发送到指定的虚拟专用网关。**  

```
Set-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 10.0.0.0/24 -GatewayId vgw-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ReplaceRoute](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-EC2RouteTableAssociation`
<a name="ec2_ReplaceRouteTableAssociation_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-EC2RouteTableAssociation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的路由表与指定路由表关联的子网相关联。**  

```
Set-EC2RouteTableAssociation -RouteTableId rtb-1a2b3c4d -AssociationId rtbassoc-12345678
```
**输出**：  

```
rtbassoc-87654321
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ReplaceRouteTableAssociation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-EC2Instance`
<a name="ec2_StartInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-EC2Instance`。

**适用于 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 参数创建过滤器。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "instance-state-name"
$filter.Values = "stopped"

(Get-EC2Instance -Filter $filter).Instances | Start-EC2Instance
```
**示例 5：此示例验证了在不实际启动 EC2 实例的情况下使用 DryRun 参数启动实例的权限。注：这在操作成功时会引发异常，这是预期行为。**  

```
Start-EC2Instance -InstanceId 'i-0abcdef123456' -Region 'us-west-1' -DryRun $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StartInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-EC2InstanceMonitoring`
<a name="ec2_MonitorInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-EC2InstanceMonitoring`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用对指定实例的详细监控。**  

```
Start-EC2InstanceMonitoring -InstanceId i-12345678
```
**输出**：  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [MonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-EC2ImportTask`
<a name="ec2_CancelImportTask_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-EC2ImportTask`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例取消指定的导入任务（快照或映像导入）。如果需要，可以使用 `-CancelReason` 参数提供原因。**  

```
Stop-EC2ImportTask -ImportTaskId import-ami-abcdefgh
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CancelImportTask](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-EC2Instance`
<a name="ec2_StopInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-EC2Instance`。

**适用于 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 参考 (V* 5) [StopInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-EC2InstanceMonitoring`
<a name="ec2_UnmonitorInstances_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-EC2InstanceMonitoring`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁用对指定实例的详细监控。**  

```
Stop-EC2InstanceMonitoring -InstanceId i-12345678
```
**输出**：  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UnmonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-EC2SpotFleetRequest`
<a name="ec2_CancelSpotFleetRequests_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-EC2SpotFleetRequest`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例取消指定的竞价型实例集请求并终止关联的竞价型实例。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $true
```
**示例 2：此示例取消指定的竞价型实例集请求，但不终止关联的竞价型实例。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CancelSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-EC2SpotInstanceRequest`
<a name="ec2_CancelSpotInstanceRequests_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-EC2SpotInstanceRequest`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例取消指定的竞价型实例请求。**  

```
Stop-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**输出**：  

```
SpotInstanceRequestId    State
---------------------    -----
sir-12345678             cancelled
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CancelSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-EC2Address`
<a name="ec2_DisassociateAddress_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-EC2Address`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的弹性 IP 地址与 VPC 中的指定实例取消关联。**  

```
Unregister-EC2Address -AssociationId eipassoc-12345678
```
**示例 2：此示例在 EC2-Classic 中取消指定弹性 IP 地址与指定实例的关联。**  

```
Unregister-EC2Address -PublicIp 203.0.113.17
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisassociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-EC2Image`
<a name="ec2_DeregisterImage_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-EC2Image`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例取消注册指定的 AMI。**  

```
Unregister-EC2Image -ImageId ami-12345678
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeregisterImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-EC2PrivateIpAddress`
<a name="ec2_UnassignPrivateIpAddresses_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-EC2PrivateIpAddress`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从指定的网络接口取消分配指定的私有 IP 地址。**  

```
Unregister-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UnassignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-EC2RouteTable`
<a name="ec2_DisassociateRouteTable_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-EC2RouteTable`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例移除路由表和子网之间的指定关联。**  

```
Unregister-EC2RouteTable -AssociationId rtbassoc-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisassociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-EC2SecurityGroupRuleIngressDescription`
<a name="ec2_UpdateSecurityGroupRuleDescriptionsIngress_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-EC2SecurityGroupRuleIngressDescription`。

**适用于 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 参考 (V* 5) [UpdateSecurityGroupRuleDescriptionsIngress](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用 PowerShell 于 V5 的工具的 Amazon ECR 示例
<a name="powershell_ecr_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon ECR 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-ECRLoginCommand`
<a name="ecr_Get-ECRLoginCommand_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ECRLoginCommand`。

**适用于 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 注册表，您就可以指定任何 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* [-ECRLogin 命令](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用适用于 PowerShell V5 的工具的 Amazon ECS 示例
<a name="powershell_ecs_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon ECS 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-ECSClusterDetail`
<a name="ecs_DescribeClusters_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ECSClusterDetail`。

**适用于 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 参考 (V* 5) [DescribeClusters](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ECSClusterList`
<a name="ecs_ListClusters_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ECSClusterList`。

**适用于 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 参考 (V* 5) [ListClusters](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ECSClusterService`
<a name="ecs_ListServices_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ECSClusterService`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出在默认集群中运行的所有服务。**  

```
Get-ECSClusterService
```
**示例 2：此示例列出在指定集群中运行的所有服务。**  

```
Get-ECSClusterService -Cluster myCluster
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListServices](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ECSService`
<a name="ecs_DescribeServices_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ECSService`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例演示如何从默认集群中检索特定服务的详细信息。**  

```
Get-ECSService -Service my-hhtp-service
```
**示例 2：此示例演示如何检索在指定集群中运行的特定服务的详细信息。**  

```
Get-ECSService -Cluster myCluster -Service my-hhtp-service
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ECSCluster`
<a name="ecs_CreateCluster_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ECSCluster`。

**适用于 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 参考 (V* 5) [CreateCluster](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ECSService`
<a name="ecs_CreateService_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ECSService`。

**适用于 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 参考 (V* 5) [CreateService](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ECSCluster`
<a name="ecs_DeleteCluster_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ECSCluster`。

**适用于 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 参考 (V* 5) [DeleteCluster](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ECSService`
<a name="ecs_DeleteService_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ECSService`。

**适用于 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 参考 (V* 5) [DeleteService](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-ECSClusterSetting`
<a name="ecs_UpdateClusterSettings_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-ECSClusterSetting`。

**适用于 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 参考 (V* 5) [UpdateClusterSettings](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-ECSService`
<a name="ecs_UpdateService_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-ECSService`。

**适用于 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 参考 (V* 5) [UpdateService](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Amazon EFS 示例
<a name="powershell_efs_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon EFS 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Edit-EFSMountTargetSecurityGroup`
<a name="efs_ModifyMountTargetSecurityGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-EFSMountTargetSecurityGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：更新对指定挂载目标有效的安全组。最多可以指定 5 个，格式为“sg-xxxxxxxx”。**  

```
Edit-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d -SecurityGroup sg-group1,sg-group3
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EFSFileSystem`
<a name="efs_DescribeFileSystems_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EFSFileSystem`。

**适用于 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 参考 (V* 5) [DescribeFileSystems](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EFSMountTarget`
<a name="efs_DescribeMountTargets_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EFSMountTarget`。

**适用于 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 参考 (V* 5) [DescribeMountTargets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EFSMountTargetSecurityGroup`
<a name="efs_DescribeMountTargetSecurityGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EFSMountTargetSecurityGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回安全组的 ID，这些安全组当前分配给与挂载目标关联的网络接口。**  

```
Get-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d
```
**输出**：  

```
sg-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EFSTag`
<a name="efs_DescribeTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EFSTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回当前与指定文件系统关联的标签集合。**  

```
Get-EFSTag -FileSystemId fs-1a2b3c4d
```
**输出**：  

```
Key         Value
---         -----
Name        My File System
tagkey1     tagvalue1
tagkey2     tagvalue2
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EFSFileSystem`
<a name="efs_CreateFileSystem_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EFSFileSystem`。

**适用于 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 参考 (V* 5) [CreateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EFSMountTarget`
<a name="efs_CreateMountTarget_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EFSMountTarget`。

**适用于 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 参考 (V* 5) [CreateMountTarget](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EFSTag`
<a name="efs_CreateTags_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EFSTag`。

**适用于 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 参考 (V* 5) [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EFSFileSystem`
<a name="efs_DeleteFileSystem_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EFSFileSystem`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除不再使用的指定文件系统（如果文件系统有挂载目标，则必须先将其移除）。在 cmdlet 继续运行之前，系统将提示您进行确认 - 要禁止确认，请使用 `-Force` 开关。**  

```
Remove-EFSFileSystem -FileSystemId fs-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EFSMountTarget`
<a name="efs_DeleteMountTarget_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EFSMountTarget`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的挂载目标。在操作继续之前，系统会提示您进行确认。要禁止提示，请使用 `-Force` 开关。请注意，此操作通过目标来强制中断文件系统的所有挂载 - 如果可行，您可能需要考虑在运行此命令之前卸载文件系统。**  

```
Remove-EFSMountTarget -MountTargetId fsmt-1a2b3c4d
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteMountTarget](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EFSTag`
<a name="efs_DeleteTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EFSTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：从文件系统中删除包含一个或多个标签的集合。在 cmdlet 继续运行之前，系统将提示您进行确认 - 要禁止确认，请使用 `-Force` 开关。**  

```
Remove-EFSTag -FileSystemId fs-1a2b3c4d -TagKey "tagkey1","tagkey2"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Amazon EKS 示例
<a name="powershell_eks_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon EKS 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-EKSResourceTag`
<a name="eks_TagResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-EKSResourceTag`。

**适用于 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 参考 (V* 5) [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSCluster`
<a name="eks_DescribeCluster_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSCluster`。

**适用于 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 参考 (V* 5) [DescribeCluster](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSClusterList`
<a name="eks_ListClusters_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSClusterList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 列出了您在 AWS 账户 指定区域内的 Amazon EKS 集群。**  

```
Get-EKSClusterList
```
**输出**：  

```
 PROD
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListClusters](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSFargateProfile`
<a name="eks_DescribeFargateProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSFargateProfile`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 返回有关 Far AWS gate 配置文件的描述性信息。**  

```
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 参考 (V* 5) [DescribeFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSFargateProfileList`
<a name="eks_ListFargateProfiles_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSFargateProfileList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 列出了与指定区域中指定集群关联的 AWS Fargate 配置文件。 AWS 账户 **  

```
Get-EKSFargateProfileList -ClusterName "TEST"
```
**输出**：  

```
EKSFargate
EKSFargateProfile
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListFargateProfiles](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSNodegroup`
<a name="eks_DescribeNodegroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSNodegroup`。

**适用于 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 参考 (V* 5) [DescribeNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSNodegroupList`
<a name="eks_ListNodegroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSNodegroupList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 列出了与您在 AWS 账户 指定区域中的指定集群关联的 Amazon EKS 节点组。**  

```
Get-EKSNodegroupList -ClusterName PROD
```
**输出**：  

```
 ProdEKSNodeGroup
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListNodegroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSResourceTag`
<a name="eks_ListTagsForResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSResourceTag`。

**适用于 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 参考 (V* 5) [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSUpdate`
<a name="eks_DescribeUpdate_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSUpdate`。

**适用于 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 参考 (V* 5) [DescribeUpdate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-EKSUpdateList`
<a name="eks_ListUpdates_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-EKSUpdateList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 列出了在指定区域中与您 AWS 账户的 Amazon EKS 集群或托管节点组相关的更新。**  

```
Get-EKSUpdateList -Name "PROD"
```
**输出**：  

```
ee708232-7d2e-4ed7-9270-d0b5176f0726
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListUpdates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EKSCluster`
<a name="eks_CreateCluster_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EKSCluster`。

**适用于 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 参考 (V* 5) [CreateCluster](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EKSFargateProfile`
<a name="eks_CreateFargateProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EKSFargateProfile`。

**适用于 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 参考 (V* 5) [CreateFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-EKSNodeGroup`
<a name="eks_CreateNodegroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-EKSNodeGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 为 Amazon EKS 集群创建托管式 Worker 节点组。您只能为集群创建等于集群的当前 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 参考 (V* 5) [CreateNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EKSCluster`
<a name="eks_DeleteCluster_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EKSCluster`。

**适用于 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 参考 (V* 5) [DeleteCluster](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EKSFargateProfile`
<a name="eks_DeleteFargateProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EKSFargateProfile`。

**适用于 PowerShell V5 的工具**  
**示例 1：此 cmdlet 删除了 Fargate 配置文件 AWS 。删除 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 参考 (V* 5) [DeleteFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EKSNodegroup`
<a name="eks_DeleteNodegroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EKSNodegroup`。

**适用于 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 参考 (V* 5) [DeleteNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-EKSResourceTag`
<a name="eks_UntagResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-EKSResourceTag`。

**适用于 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 参考 (V* 5) [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-EKSClusterConfig`
<a name="eks_UpdateClusterConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-EKSClusterConfig`。

**适用于 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 参考 (V* 5) [UpdateClusterConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-EKSClusterVersion`
<a name="eks_UpdateClusterVersion_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-EKSClusterVersion`。

**适用于 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 参考 (V* 5) [UpdateClusterVersion](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# Elastic Load Balancing-使用适用于 PowerShell V5 的工具的版本 1 示例
<a name="powershell_elastic-load-balancing_code_examples"></a>

以下代码示例向您展示了如何使用带有 Elastic Load Balancing 的 AWS Tools for PowerShell V5-版本 1 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-ELBLoadBalancerToSubnet`
<a name="elastic-load-balancing_AttachLoadBalancerToSubnets_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-ELBLoadBalancerToSubnet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的子网添加到为指定的负载均衡器配置的子网集。输出包括子网的完整列表。**  

```
Add-ELBLoadBalancerToSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**输出**：  

```
subnet-12345678
subnet-87654321
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachLoadBalancerToSubnets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-ELBResourceTag`
<a name="elastic-load-balancing_AddTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-ELBResourceTag`。

**适用于 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 = 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 参考 (V* 5) [AddTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_DisableAvailabilityZonesForLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-ELBAvailabilityZoneForLoadBalancer`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从指定的负载均衡器移除指定的可用区。输出包括剩余的可用区。**  

```
Disable-ELBAvailabilityZoneForLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a
```
**输出**：  

```
us-west-2b
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Dismount-ELBLoadBalancerFromSubnet`
<a name="elastic-load-balancing_DetachLoadBalancerFromSubnets_powershell_topic"></a>

以下代码示例演示了如何使用 `Dismount-ELBLoadBalancerFromSubnet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从为指定负载均衡器配置的子网集中删除指定的子网。输出包括其余子网。**  

```
Dismount-ELBLoadBalancerFromSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**输出**：  

```
subnet-87654321
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DetachLoadBalancerFromSubnets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_ModifyLoadBalancerAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-ELBLoadBalancerAttribute`。

**适用于 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 参考 (V* 5) [ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_EnableAvailabilityZonesForLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-ELBAvailabilityZoneForLoadBalancer`。

**适用于 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 参考 (V* 5) [EnableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELBInstanceHealth`
<a name="elastic-load-balancing_DescribeInstanceHealth_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELBInstanceHealth`。

**适用于 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 参考 (V* 5) [DescribeInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELBLoadBalancer`
<a name="elastic-load-balancing_DescribeLoadBalancers_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELBLoadBalancer`。

**适用于 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 参考 (V* 5) [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_DescribeLoadBalancerAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELBLoadBalancerAttribute`。

**适用于 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 参考 (V* 5) [DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELBLoadBalancerPolicy`。

**适用于 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 参考 (V* 5) [DescribeLoadBalancerPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELBLoadBalancerPolicyType`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicyTypes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELBLoadBalancerPolicyType`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取弹性负载均衡支持的策略类型。**  

```
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 参考 (V* 5) [DescribeLoadBalancerPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELBResourceTag`
<a name="elastic-load-balancing_DescribeTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELBResourceTag`。

**适用于 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 参考 (V* 5) [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Join-ELBSecurityGroupToLoadBalancer`
<a name="elastic-load-balancing_ApplySecurityGroupsToLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `Join-ELBSecurityGroupToLoadBalancer`。

**适用于 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 参考 (V* 5) [ApplySecurityGroupsToLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELBAppCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateAppCookieStickinessPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELBAppCookieStickinessPolicy`。

**适用于 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 参考 (V* 5) [CreateAppCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELBLBCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateLbCookieStickinessPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELBLBCookieStickinessPolicy`。

**适用于 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 参考 (V* 5) [CreateLbCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELBLoadBalancer`
<a name="elastic-load-balancing_CreateLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELBLoadBalancer`。

**适用于 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 参考 (V* 5) [CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELBLoadBalancerListener`
<a name="elastic-load-balancing_CreateLoadBalancerListeners_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELBLoadBalancerListener`。

**适用于 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 参考 (V* 5) [CreateLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_CreateLoadBalancerPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELBLoadBalancerPolicy`。

**适用于 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 参考 (V* 5) [CreateLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-ELBInstanceWithLoadBalancer`
<a name="elastic-load-balancing_RegisterInstancesWithLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-ELBInstanceWithLoadBalancer`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例向指定的负载均衡器注册指定 EC2 实例。**  

```
Register-ELBInstanceWithLoadBalancer -LoadBalancerName my-load-balancer -Instance i-12345678
```
**输出**：  

```
InstanceId
----------
i-12345678
i-87654321
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RegisterInstancesWithLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELBInstanceFromLoadBalancer`
<a name="elastic-load-balancing_DeregisterInstancesFromLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELBInstanceFromLoadBalancer`。

**适用于 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 参考 (V* 5) [DeregisterInstancesFromLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELBLoadBalancer`
<a name="elastic-load-balancing_DeleteLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELBLoadBalancer`。

**适用于 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 参考 (V* 5) [DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELBLoadBalancerListener`
<a name="elastic-load-balancing_DeleteLoadBalancerListeners_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELBLoadBalancerListener`。

**适用于 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 参考 (V* 5) [DeleteLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DeleteLoadBalancerPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELBLoadBalancerPolicy`。

**适用于 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 参考 (V* 5) [DeleteLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELBResourceTag`
<a name="elastic-load-balancing_RemoveTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELBResourceTag`。

**适用于 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 参考 (V* 5) [RemoveTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELBHealthCheck`
<a name="elastic-load-balancing_ConfigureHealthCheck_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELBHealthCheck`。

**适用于 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 参考 (V* 5) [ConfigureHealthCheck](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELBLoadBalancerListenerSSLCertificate`
<a name="elastic-load-balancing_SetLoadBalancerListenerSslCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELBLoadBalancerListenerSSLCertificate`。

**适用于 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 参考 (V* 5) [SetLoadBalancerListenerSslCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELBLoadBalancerPolicyForBackendServer`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesForBackendServer_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELBLoadBalancerPolicyForBackendServer`。

**适用于 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 参考 (V* 5) [SetLoadBalancerPoliciesForBackendServer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELBLoadBalancerPolicyOfListener`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesOfListener_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELBLoadBalancerPolicyOfListener`。

**适用于 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 参考 (V* 5) [SetLoadBalancerPoliciesOfListener](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# Elastic Load Balancing-使用适用于 PowerShell V5 的工具的版本 2 示例
<a name="powershell_elastic-load-balancing-v2_code_examples"></a>

以下代码示例向您展示了如何使用带有 Elastic Load Balancing 的 AWS Tools for PowerShell V5-版本 2 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_AddListenerCertificates_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-ELB2ListenerCertificate`。

**适用于 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 参考 (V* 5) [AddListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-ELB2Tag`
<a name="elastic-load-balancing-v2_AddTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-ELB2Tag`。

**适用于 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 参考 (V* 5) [AddTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-ELB2Listener`
<a name="elastic-load-balancing-v2_ModifyListener_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-ELB2Listener`。

**适用于 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 参考 (V* 5) [ModifyListener](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_ModifyLoadBalancerAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-ELB2LoadBalancerAttribute`。

**适用于 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 参考 (V* 5) [ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-ELB2Rule`
<a name="elastic-load-balancing-v2_ModifyRule_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-ELB2Rule`。

**适用于 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 参考 (V* 5) [ModifyRule](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_ModifyTargetGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-ELB2TargetGroup`。

**适用于 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 参考 (V* 5) [ModifyTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_ModifyTargetGroupAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-ELB2TargetGroupAttribute`。

**适用于 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 参考 (V* 5) [ModifyTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2AccountLimit`
<a name="elastic-load-balancing-v2_DescribeAccountLimits_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2AccountLimit`。

**适用于 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 参考 (V* 5) [DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2Listener`
<a name="elastic-load-balancing-v2_DescribeListeners_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2Listener`。

**适用于 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 参考 (V* 5) [DescribeListeners](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_DescribeListenerCertificates_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2ListenerCertificate`。

**适用于 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 参考 (V* 5) [DescribeListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2LoadBalancer`。

**适用于 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 参考 (V* 5) [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_DescribeLoadBalancerAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2LoadBalancerAttribute`。

**适用于 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 参考 (V* 5) [DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2Rule`
<a name="elastic-load-balancing-v2_DescribeRules_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2Rule`。

**适用于 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 参考 (V* 5) [DescribeRules](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2SSLPolicy`
<a name="elastic-load-balancing-v2_DescribeSslPolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2SSLPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出了 ElasticLoadBalancing V2 的所有可用侦听器策略。**  

```
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 参考 (V* 5) [DescribeSslPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2Tag`
<a name="elastic-load-balancing-v2_DescribeTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2Tag`。

**适用于 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 参考 (V* 5) [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DescribeTargetGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2TargetGroup`。

**适用于 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 参考 (V* 5) [DescribeTargetGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_DescribeTargetGroupAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2TargetGroupAttribute`。

**适用于 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 参考 (V* 5) [DescribeTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ELB2TargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ELB2TargetHealth`。

**适用于 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 参考 (V* 5) [DescribeTargetHealth](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELB2Listener`
<a name="elastic-load-balancing-v2_CreateListener_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELB2Listener`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建新的 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 参考 (V* 5) [CreateListener](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELB2LoadBalancer`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建具有两个子网、面向互联网的新应用程序负载均衡器。**  

```
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 参考 (V* 5) [CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELB2Rule`
<a name="elastic-load-balancing-v2_CreateRule_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELB2Rule`。

**适用于 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 参考 (V* 5) [CreateRule](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ELB2TargetGroup`。

**适用于 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 参考 (V* 5) [CreateTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-ELB2Target`
<a name="elastic-load-balancing-v2_RegisterTargets_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-ELB2Target`。

**适用于 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 参考 (V* 5) [RegisterTargets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELB2Listener`
<a name="elastic-load-balancing-v2_DeleteListener_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELB2Listener`。

**适用于 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 参考 (V* 5) [DeleteListener](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_RemoveListenerCertificates_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELB2ListenerCertificate`。

**适用于 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 参考 (V* 5) [RemoveListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELB2LoadBalancer`。

**适用于 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 参考 (V* 5) [DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELB2Rule`
<a name="elastic-load-balancing-v2_DeleteRule_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELB2Rule`。

**适用于 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 参考 (V* 5) [DeleteRule](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELB2Tag`
<a name="elastic-load-balancing-v2_RemoveTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELB2Tag`。

**适用于 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 参考 (V* 5) [RemoveTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-ELB2TargetGroup`。

**适用于 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 参考 (V* 5) [DeleteTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELB2IpAddressType`
<a name="elastic-load-balancing-v2_SetIpAddressType_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELB2IpAddressType`。

**适用于 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 参考 (V* 5) [SetIpAddressType](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELB2RulePriority`
<a name="elastic-load-balancing-v2_SetRulePriorities_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELB2RulePriority`。

**适用于 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 参考 (V* 5) [SetRulePriorities](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELB2SecurityGroup`
<a name="elastic-load-balancing-v2_SetSecurityGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELB2SecurityGroup`。

**适用于 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 参考 (V* 5) [SetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-ELB2Subnet`
<a name="elastic-load-balancing-v2_SetSubnets_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-ELB2Subnet`。

**适用于 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 参考 (V* 5) [SetSubnets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-ELB2Target`
<a name="elastic-load-balancing-v2_DeregisterTargets_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-ELB2Target`。

**适用于 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 参考 (V* 5) [DeregisterTargets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的亚马逊 FSx 示例
<a name="powershell_fsx_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon FSx 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-FSXResourceTag`
<a name="fsx_TagResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-FSXResourceTag`。

**适用于 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 参考 (V* 5) [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-FSXBackup`
<a name="fsx_DescribeBackups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-FSXBackup`。

**适用于 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 参考 (V* 5) [DescribeBackups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-FSXFileSystem`
<a name="fsx_DescribeFileSystems_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-FSXFileSystem`。

**适用于 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 参考 (V* 5) [DescribeFileSystems](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-FSXResourceTagList`
<a name="fsx_ListTagsForResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-FSXResourceTagList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出所提供的资源 arn 的标签。**  

```
Get-FSXResourceTagList -ResourceARN $fsx.ResourceARN
```
**输出**：  

```
Key         Value
---         -----
FSx-Service Windows
Users       Dev
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-FSXBackup`
<a name="fsx_CreateBackup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-FSXBackup`。

**适用于 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 参考 (V* 5) [CreateBackup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-FSXFileSystem`
<a name="fsx_CreateFileSystem_powershell_topic"></a>

以下代码示例演示了如何使用 `New-FSXFileSystem`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建一个新的 300 GB Windows 文件系统，容许从指定的子网进行访问，支持高达每秒 8 兆字节的吞吐量。新的文件系统将自动加入指定的 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 参考 (V* 5) [CreateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-FSXFileSystemFromBackup`
<a name="fsx_CreateFileSystemFromBackup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-FSXFileSystemFromBackup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用现有的 Amazon FSx for Windows 文件服务器备份创建新的亚马逊 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 参考 (V* 5) [CreateFileSystemFromBackup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-FSXBackup`
<a name="fsx_DeleteBackup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-FSXBackup`。

**适用于 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 参考 (V* 5) [DeleteBackup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-FSXFileSystem`
<a name="fsx_DeleteFileSystem_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-FSXFileSystem`。

**适用于 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 参考 (V* 5) [DeleteFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-FSXResourceTag`
<a name="fsx_UntagResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-FSXResourceTag`。

**适用于 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 参考 (V* 5) [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-FSXFileSystem`
<a name="fsx_UpdateFileSystem_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-FSXFileSystem`。

**适用于 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 参考 (V* 5) [UpdateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Amazon Glacier 示例
<a name="powershell_glacier_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon Glacier 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-GLCJob`
<a name="glacier_DescribeJob_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-GLCJob`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定任务的详细信息。任务成功完成后，可以使用 Read-O GCJob utput 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 参考 (V* 5) [DescribeJob](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-GLCVault`
<a name="glacier_CreateVault_powershell_topic"></a>

以下代码示例演示了如何使用 `New-GLCVault`。

**适用于 PowerShell V5 的工具**  
**示例 1：为用户账户创建新文件库。由于未向-AccountId 参数提供任何值，因此 cmdlet 使用默认值 “-” 来表示当前账户。**  

```
New-GLCVault -VaultName myvault
```
**输出**：  

```
/01234567812/vaults/myvault
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateVault](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Read-GLCJobOutput`
<a name="glacier_GetJobOutput_powershell_topic"></a>

以下代码示例演示了如何使用 `Read-GLCJobOutput`。

**适用于 PowerShell V5 的工具**  
**示例 1：下载计划在指定任务中检索的档案内容，并将这些内容存储到磁盘上的文件中。如果有校验和，则下载会为您验证校验和。如果需要，可以通过指定 `-Select '*'` 来返回包括校验和在内的整个响应。**  

```
Read-GLCJobOutput -VaultName myvault -JobId "HSWjArc...Zq2XLiW" -FilePath "c:\temp\blue.bin"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetJobOutput](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-GLCJob`
<a name="glacier_InitiateJob_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-GLCJob`。

**适用于 PowerShell V5 的工具**  
**示例 1：启动一项任务，从用户拥有的指定文件库中检索档案。可以使用 Get-GLCJob cmdlet 检查作业的状态。任务成功完成后，可以使用读取-GCJob 输出 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 参考 (V* 5) [InitiateJob](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-GLCArchive`
<a name="glacier_UploadArchive_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-GLCArchive`。

**适用于 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 参考 (V* 5) [UploadArchive](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS Glue 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_glue_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS Glue的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `New-GLUEJob`
<a name="glue_CreateJob_powershell_topic"></a>

以下代码示例演示了如何使用 `New-GLUEJob`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在 AWS Glue 中创建了一个新作业。命令名称的值始终为`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 参考 (V* 5) [CreateJob](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS Health 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_health_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS Health的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-HLTHEvent`
<a name="health_DescribeEvents_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-HLTHEvent`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令从 Person AWS al Health Dashboard 返回事件。用户添加 -Region 参数以查看美国东部（弗吉尼亚州北部）区域中可用于服务的事件，而 -Filter\$1Region 参数筛选在欧洲地区（伦敦）和美国西部（俄勒冈州）区域（eu-west-2 和 us-west-2）中记录的事件。-Filter\$1 StartTime 参数筛选事件可以开始的时间范围，而-Filter\$1 EndTime 参数则筛选事件可能结束的时间范围。结果是 RDS 的计划维护事件，该事件在指定的-Filter\$1 StartTime 范围内开始，并在计划的-Filter\$1 范围内结束。EndTime **  

```
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 参考 (V* 5) [DescribeEvents](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 IAM 示例
<a name="powershell_iam_code_examples"></a>

以下代码示例向您展示了如何使用带有 IAM 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-IAMClientIDToOpenIDConnectProvider`
<a name="iam_AddClientIdToOpenIdConnectProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-IAMClientIDToOpenIDConnectProvider`。

**适用于 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 参考 (V* 5) [AddClientIdToOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-IAMRoleTag`
<a name="iam_TagRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-IAMRoleTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在身份管理服务中为角色添加标签**  

```
Add-IAMRoleTag -RoleName AdminRoleacess -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [TagRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-IAMRoleToInstanceProfile`
<a name="iam_AddRoleToInstanceProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-IAMRoleToInstanceProfile`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令将名为 `S3Access` 的角色添加到名为 `webserver` 的现有实例配置文件中。要创建实例配置文件，请使用 `New-IAMInstanceProfile` 命令。使用此命令创建实例配置文件并将其与角色关联后，您可以将其附加到 EC2 实例。为此，请使用带有 `InstanceProfile_Arn` 或 `InstanceProfile-Name` 参数的 `New-EC2Instance` cmdlet 来启动新实例。**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AddRoleToInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-IAMUserTag`
<a name="iam_TagUser_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-IAMUserTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在身份管理服务中为用户添加标签**  

```
Add-IAMUserTag -UserName joe -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [TagUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Add-IAMUserToGroup`
<a name="iam_AddUserToGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-IAMUserToGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令将名为 `Bob` 的用户添加到名为 `Admins` 的组中。**  

```
Add-IAMUserToGroup -UserName "Bob" -GroupName "Admins"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AddUserToGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Disable-IAMMFADevice`
<a name="iam_DeactivateMfaDevice_powershell_topic"></a>

以下代码示例演示了如何使用 `Disable-IAMMFADevice`。

**适用于 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 设备，然后才能为同一用户创建新的虚拟 MFA 设备。**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeactivateMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-IAMPassword`
<a name="iam_ChangePassword_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-IAMPassword`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令更改运行该命令的用户的密码。此命令只能由 IAM 用户调用。如果您在使用 AWS 账户（根）凭据登录时调用此命令，则该命令将返回错误。`InvalidUserType`**  

```
Edit-IAMPassword -OldPassword "MyOldP@ssw0rd" -NewPassword "MyNewP@ssw0rd"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ChangePassword](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Enable-IAMMFADevice`
<a name="iam_EnableMfaDevice_powershell_topic"></a>

以下代码示例演示了如何使用 `Enable-IAMMFADevice`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令启用序列号为 `987654321098` 的硬件 MFA 设备，并将该设备与用户 `Bob` 关联。它包含设备中按顺序排列的前两个代码。**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**示例 2：此示例创建并启用虚拟 MFA 设备。第一条命令创建虚拟设备并在变量 `$MFADevice` 中返回设备的对象表示形式。您可以使用 `.Base32StringSeed` 或 `QRCodePng` 属性来配置用户的软件应用程序。最后一条命令将该设备分配给用户 `David`，通过其序列号识别设备。该命令还 AWS 通过按顺序包含虚拟 MFA 设备中的前两个代码来与设备同步。**  

```
$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 参考 (V* 5) [EnableMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAccessKey`
<a name="iam_ListAccessKeys_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAccessKey`。

**适用于 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 参考 (V* 5) [ListAccessKeys](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAccessKeyLastUsed`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回所提供访问密钥的拥有用户名和上次使用信息。**  

```
Get-IAMAccessKeyLastUsed -AccessKeyId ABCDEXAMPLE
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetAccessKeyLastUsed](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAccountAlias`
<a name="iam_ListAccountAliases_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAccountAlias`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回 AWS 账户的账户别名。**  

```
Get-IAMAccountAlias
```
**输出**：  

```
ExampleCo
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListAccountAliases](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAccountAuthorizationDetail`
<a name="iam_GetAccountAuthorizationDetails_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAccountAuthorizationDetail`。

**适用于 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 参考 (V* 5) [GetAccountAuthorizationDetails](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAccountPasswordPolicy`。

**适用于 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 参考 (V* 5) [GetAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAccountSummary`
<a name="iam_GetAccountSummary_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAccountSummary`。

**适用于 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 参考 (V* 5) [GetAccountSummary](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAttachedGroupPolicyList`
<a name="iam_ListAttachedGroupPolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAttachedGroupPolicyList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回挂载到 AWS 账户中名为 IAM 组的托管策略`Admins`的名称和 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 参考 (V* 5) [ListAttachedGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAttachedRolePolicyList`
<a name="iam_ListAttachedRolePolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAttachedRolePolicyList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回 AWS 账户中名为 IAM 角色的名称和 ARNs 关联`SecurityAuditRole`的托管策略。要查看嵌入在角色中的内联策略的列表，请使用 `Get-IAMRolePolicyList` 命令。**  

```
Get-IAMAttachedRolePolicyList -RoleName "SecurityAuditRole"
```
**输出**：  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListAttachedRolePolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMAttachedUserPolicyList`
<a name="iam_ListAttachedUserPolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMAttachedUserPolicyList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回 AWS 账户`Bob`中名为 IAM 用户的名称和 ARNs 托管策略。要查看嵌入在 IAM 用户中的内联策略的列表，请使用 `Get-IAMUserPolicyList` 命令。**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**输出**：  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListAttachedUserPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMContextKeysForCustomPolicy`
<a name="iam_GetContextKeysForCustomPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMContextKeysForCustomPolicy`。

**适用于 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 参考 (V* 5) [GetContextKeysForCustomPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMContextKeysForPrincipalPolicy`
<a name="iam_GetContextKeysForPrincipalPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMContextKeysForPrincipalPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取所提供的策略 json 中和附加到 IAM 实体（用户/角色等）的策略中存在的所有上下文键。For-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 参考 (V* 5) [GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMCredentialReport`
<a name="iam_GetCredentialReport_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMCredentialReport`。

**适用于 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 参考 (V* 5) [GetCredentialReport](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMEntitiesForPolicy`
<a name="iam_ListEntitiesForPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMEntitiesForPolicy`。

**适用于 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 参考 (V* 5) [ListEntitiesForPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMGroup`
<a name="iam_GetGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMGroup`。

**适用于 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 参考 (V* 5) [GetGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMGroupForUser`
<a name="iam_ListGroupsForUser_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMGroupForUser`。

**适用于 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 参考 (V* 5) [ListGroupsForUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMGroupList`
<a name="iam_ListGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMGroupList`。

**适用于 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 参考 (V* 5) [ListGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMGroupPolicy`
<a name="iam_GetGroupPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMGroupPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回有关组 `Testers` 的名为 `PowerUserAccess-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 参考 (V* 5) [GetGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMGroupPolicyList`
<a name="iam_ListGroupPolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMGroupPolicyList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回嵌入组 `Testers` 中的内联策略的列表。要获取附加到该组的托管策略，请使用命令 `Get-IAMAttachedGroupPolicyList`。**  

```
Get-IAMGroupPolicyList -GroupName Testers
```
**输出**：  

```
Deny-Assume-S3-Role-In-Production
PowerUserAccess-Testers
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMInstanceProfile`
<a name="iam_GetInstanceProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMInstanceProfile`。

**适用于 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 参考 (V* 5) [GetInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMInstanceProfileForRole`
<a name="iam_ListInstanceProfilesForRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMInstanceProfileForRole`。

**适用于 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 参考 (V* 5) [ListInstanceProfilesForRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMInstanceProfileList`
<a name="iam_ListInstanceProfiles_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMInstanceProfileList`。

**适用于 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 参考 (V* 5) [ListInstanceProfiles](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMLoginProfile`
<a name="iam_GetLoginProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMLoginProfile`。

**适用于 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 参考 (V* 5) [GetLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMMFADevice`
<a name="iam_ListMfaDevices_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMMFADevice`。

**适用于 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 参考 (V* 5) [ListMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMOpenIDConnectProvider`
<a name="iam_GetOpenIdConnectProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMOpenIDConnectProvider`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回有关 ARN 为 `arn:aws:iam::123456789012:oidc-provider/accounts.google.com` 的 OpenID Connect 提供者的详细信息。该`ClientIDList`属性是一个集合，其中包含为此提供者 IDs 定义的所有客户端。**  

```
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 参考 (V* 5) [GetOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMOpenIDConnectProviderList`
<a name="iam_ListOpenIdConnectProviders_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMOpenIDConnectProviderList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回当前 AWS 账户账户中定义的所有 OpenID Connect 提供者的 ARN 列表。**  

```
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 参考 (V* 5) [ListOpenIdConnectProviders](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMPolicy`
<a name="iam_GetPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMPolicy`。

**适用于 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 参考 (V* 5) [GetPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMPolicyList`
<a name="iam_ListPolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMPolicyList`。

**适用于 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 参考 (V* 5) [ListPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMPolicyVersion`
<a name="iam_GetPolicyVersion_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMPolicyVersion`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将返回 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 参考 (V* 5) [GetPolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMPolicyVersionList`
<a name="iam_ListPolicyVersions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMPolicyVersionList`。

**适用于 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 参考 (V* 5) [ListPolicyVersions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMRole`
<a name="iam_GetRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMRole`。

**适用于 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 参考 (V* 5) [GetRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMRoleList`
<a name="iam_ListRoles_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMRoleList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例检索 AWS 账户中的所有 IAM 角色列表。**  

```
Get-IAMRoleList
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListRoles](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMRolePolicy`
<a name="iam_GetRolePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMRolePolicy`。

**适用于 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 参考 (V* 5) [GetRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMRolePolicyList`
<a name="iam_ListRolePolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMRolePolicyList`。

**适用于 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 参考 (V* 5) [ListRolePolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMRoleTagList`
<a name="iam_ListRoleTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMRoleTagList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取与角色关联的标签。**  

```
Get-IAMRoleTagList -RoleName MyRoleName
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListRoleTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMSAMLProvider`
<a name="iam_GetSamlProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMSAMLProvider`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例检索有关 ARN 为 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 参考 (V* 5) [GetSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMSAMLProviderList`
<a name="iam_ListSAMLProviders_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMSAMLProviderList`。

**适用于 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 参考文档 (V* 5) SAMLProviders 中的[列表](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-IAMServerCertificate`
<a name="iam_GetServerCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMServerCertificate`。

**适用于 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 参考 (V* 5) [GetServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMServerCertificateList`
<a name="iam_ListServerCertificates_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMServerCertificateList`。

**适用于 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 参考 (V* 5) [ListServerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMServiceLastAccessedDetail`
<a name="iam_GetServiceLastAccessedDetails_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMServiceLastAccessedDetail`。

**适用于 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 参考 (V* 5) [GetServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMServiceLastAccessedDetailWithEntity`
<a name="iam_GetServiceLastAccessedDetailsWithEntities_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMServiceLastAccessedDetailWithEntity`。

**适用于 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 参考 (V* 5) [GetServiceLastAccessedDetailsWithEntities](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMSigningCertificate`
<a name="iam_ListSigningCertificates_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMSigningCertificate`。

**适用于 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 参考 (V* 5) [ListSigningCertificates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMUser`
<a name="iam_GetUser_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMUser`。

**适用于 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 参考 (V* 5) [GetUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMUserList`
<a name="iam_ListUsers_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMUserList`。

**适用于 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 参考 (V* 5) [ListUsers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMUserPolicy`
<a name="iam_GetUserPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMUserPolicy`。

**适用于 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 参考 (V* 5) [GetUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMUserPolicyList`
<a name="iam_ListUserPolicies_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMUserPolicyList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例检索嵌入在名为 `David` 的 IAM 用户中的内联策略名称列表。**  

```
Get-IAMUserPolicyList -UserName David
```
**输出**：  

```
Davids_IAM_Admin_Policy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListUserPolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMUserTagList`
<a name="iam_ListUserTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMUserTagList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取与用户关联的标签。**  

```
Get-IAMUserTagList -UserName joe
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListUserTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-IAMVirtualMFADevice`
<a name="iam_ListVirtualMfaDevices_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-IAMVirtualMFADevice`。

**适用于 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 参考 (V* 5) [ListVirtualMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMAccessKey`
<a name="iam_CreateAccessKey_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMAccessKey`。

**适用于 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 参考 (V* 5) [CreateAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMAccountAlias`
<a name="iam_CreateAccountAlias_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMAccountAlias`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将您 AWS 账户的账户别名更改为`mycompanyaws`。用户登录页面的地址更改为 https://mycom panyaws.signin.aws.amazon.com/console。使用您的账户 ID 号而不是别名的原始 URL（https://<accountidnumber>.signin.aws.amazon.com/console）继续有效。但是，任何先前定义的基于别名的都将 URLs 停止工作。**  

```
New-IAMAccountAlias -AccountAlias mycompanyaws
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateAccountAlias](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMGroup`
<a name="iam_CreateGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMGroup`。

**适用于 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 参考 (V* 5) [CreateGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMInstanceProfile`
<a name="iam_CreateInstanceProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMInstanceProfile`。

**适用于 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 参考 (V* 5) [CreateInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMLoginProfile`
<a name="iam_CreateLoginProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMLoginProfile`。

**适用于 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 参考 (V* 5) [CreateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMOpenIDConnectProvider`
<a name="iam_CreateOpenIdConnectProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMOpenIDConnectProvider`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建一个 IAM OIDC 提供者，该提供者与位于 URL `https://example.oidcprovider.com` 中的 OIDC 兼容提供者服务和客户端 ID `my-testapp-1` 关联。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 参考 (V* 5) [CreateOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMPolicy`
<a name="iam_CreatePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMPolicy`。

**适用于 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 参考 (V* 5) [CreatePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMPolicyVersion`
<a name="iam_CreatePolicyVersion_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMPolicyVersion`。

**适用于 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 参考 (V* 5) [CreatePolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMRole`
<a name="iam_CreateRole_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMRole`。

**适用于 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 参考 (V* 5) [CreateRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMSAMLProvider`
<a name="iam_CreateSAMLProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMSAMLProvider`。

**适用于 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 的详细信息，请参阅SAMLProvider在 *AWS Tools for PowerShell Cmdlet 参考文档 (V* 5) 中[创建](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-IAMServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMServiceLinkedRole`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为自动扩缩服务创建 servicelinked 角色。**  

```
New-IAMServiceLinkedRole -AWSServiceName autoscaling.amazonaws.com -CustomSuffix RoleNameEndsWithThis -Description "My service-linked role to support autoscaling"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateServiceLinkedRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMUser`
<a name="iam_CreateUser_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMUser`。

**适用于 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 参考 (V* 5) [CreateUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-IAMVirtualMFADevice`
<a name="iam_CreateVirtualMfaDevice_powershell_topic"></a>

以下代码示例演示了如何使用 `New-IAMVirtualMFADevice`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建一个新的虚拟 MFA 设备。第 2 行和第 3 行提取虚拟 MFA 软件程序创建账户所需的 `Base32StringSeed` 值（作为二维码的替代方案）。使用该值配置程序后，从程序中获取两个连续的身份验证码。最后，使用最后一条命令将虚拟 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软件程序可以扫描此图像以创建帐户（作为手动输入Base32 StringSeed 值的替代方法）。在虚拟 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 参考 (V* 5) [CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Publish-IAMServerCertificate`
<a name="iam_UploadServerCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Publish-IAMServerCertificate`。

**适用于 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 参考 (V* 5) [UploadServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Publish-IAMSigningCertificate`
<a name="iam_UploadSigningCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Publish-IAMSigningCertificate`。

**适用于 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 参考 (V* 5) [UploadSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-IAMGroupPolicy`
<a name="iam_AttachGroupPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-IAMGroupPolicy`。

**适用于 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 参考 (V* 5) [AttachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-IAMRolePolicy`
<a name="iam_AttachRolePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-IAMRolePolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将名为的 AWS 托管策略附加`SecurityAudit`到 IAM 角色`CoSecurityAuditors`。担任该角色的用户会立即受到该策略最新版本中所定义权限的影响。**  

```
Register-IAMRolePolicy -RoleName CoSecurityAuditors -PolicyArn arn:aws:iam::aws:policy/SecurityAudit
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-IAMUserPolicy`
<a name="iam_AttachUserPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-IAMUserPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将名为的 AWS 托管策略附加`AmazonCognitoPowerUser`到 IAM 用户`Bob`。用户会立即受到该策略最新版本中所定义权限的影响。**  

```
Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMAccessKey`
<a name="iam_DeleteAccessKey_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMAccessKey`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例`AKIAIOSFODNN7EXAMPLE`从名为的用户删除带有密钥 ID 的 AWS 访问密钥对`Bob`。**  

```
Remove-IAMAccessKey -AccessKeyId AKIAIOSFODNN7EXAMPLE -UserName Bob -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMAccountAlias`
<a name="iam_DeleteAccountAlias_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMAccountAlias`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从您的账户中删除了账户别名 AWS 账户。别名为 https://mycom panyaws.signin.aws.amazon.com/console 的用户登录页面不再起作用。相反，你必须使用带有 AWS 账户 身份证号的原始 URL，网址为 https: //.signin.aws.amazon.com/console。** <accountidnumber>  

```
Remove-IAMAccountAlias -AccountAlias mycompanyaws
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteAccountAlias](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMAccountPasswordPolicy`
<a name="iam_DeleteAccountPasswordPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMAccountPasswordPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了的密码策略 AWS 账户 并将所有值重置为其原始默认值。如果当前不存在密码策略，则会显示以下错误消息：找 PasswordPolicy 不到带有名称的账户策略。**  

```
Remove-IAMAccountPasswordPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMClientIDFromOpenIDConnectProvider`
<a name="iam_RemoveClientIdFromOpenIdConnectProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMClientIDFromOpenIDConnectProvider`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将客户端 ID `My-TestApp-3` 从与 ARN 为 IAM OIDC 提供商 IDs 关联的客户列表中删除。`arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com`**  

```
Remove-IAMClientIDFromOpenIDConnectProvider -ClientID My-TestApp-3 -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RemoveClientIdFromOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMGroup`
<a name="iam_DeleteGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMGroup`。

**适用于 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 参考 (V* 5) [DeleteGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMGroupPolicy`
<a name="iam_DeleteGroupPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMGroupPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从 IAM 组 `Testers` 中删除名为 `TesterPolicy` 的内联策略。该组中的用户会立即失去该策略中定义的权限。**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMInstanceProfile`
<a name="iam_DeleteInstanceProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMInstanceProfile`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除名为的 EC2 实例配置文件`MyAppInstanceProfile`。第一条命令从实例配置文件中分离所有角色，然后第二条命令删除实例配置文件。**  

```
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMLoginProfile`
<a name="iam_DeleteLoginProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMLoginProfile`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除名为 `Bob` 的 IAM 用户的登录配置文件。这会阻止用户登录控制台。 AWS 它不会阻止用户使用可能仍附加到用户账户的 AWS 访问密钥运行任何 AWS CLI PowerShell、或 API 调用。**  

```
Remove-IAMLoginProfile -UserName Bob
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMOpenIDConnectProvider`
<a name="iam_DeleteOpenIdConnectProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMOpenIDConnectProvider`。

**适用于 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 参考 (V* 5) [DeleteOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMPolicy`
<a name="iam_DeletePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMPolicy`。

**适用于 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 参考 (V* 5) [DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMPolicyVersion`
<a name="iam_DeletePolicyVersion_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMPolicyVersion`。

**适用于 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 参考 (V* 5) [DeletePolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMRole`
<a name="iam_DeleteRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMRole`。

**适用于 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 参考 (V* 5) [DeleteRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMRoleFromInstanceProfile`
<a name="iam_RemoveRoleFromInstanceProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMRoleFromInstanceProfile`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例`MyNewRole`从名为的 EC2 实例配置文件中删除名为的角色`MyNewRole`。在 IAM 控制台中创建的实例配置文件始终与角色同名，如本示例所示。如果您在 API 或 CLI 中创建实例配置文件，则其可以有不同的名称。**  

```
Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyNewRole -RoleName MyNewRole -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMRolePermissionsBoundary`
<a name="iam_DeleteRolePermissionsBoundary_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMRolePermissionsBoundary`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例展示了如何删除附加到 IAM 角色的权限边界。**  

```
Remove-IAMRolePermissionsBoundary -RoleName MyRoleName
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMRolePolicy`
<a name="iam_DeleteRolePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMRolePolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了 IAM 角色 `S3BackupRole` 中嵌入的内联策略 `S3AccessPolicy`。**  

```
Remove-IAMRolePolicy -PolicyName S3AccessPolicy -RoleName S3BackupRole
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMRoleTag`
<a name="iam_UntagRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMRoleTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从名为 “MyRoleName” 的角色中删除标签，标签键为 “abac”。要删除多个标签，请提供以逗号分隔的标签键列表。**  

```
Remove-IAMRoleTag -RoleName MyRoleName -TagKey "abac","xyzw"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UntagRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMSAMLProvider`
<a name="iam_DeleteSAMLProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMSAMLProvider`。

**适用于 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 参考文档 (V* 5) SAMLProvider 中的[删除](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-IAMServerCertificate`
<a name="iam_DeleteServerCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMServerCertificate`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除名为 `MyServerCert` 的服务器证书。**  

```
Remove-IAMServerCertificate -ServerCertificateName MyServerCert
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMServiceLinkedRole`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除服务关联角色。请注意，如果服务仍在使用此角色，则此命令将导致失败。**  

```
Remove-IAMServiceLinkedRole -RoleName AWSServiceRoleForAutoScaling_RoleNameEndsWithThis
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteServiceLinkedRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMSigningCertificate`
<a name="iam_DeleteSigningCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMSigningCertificate`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从名为 `Bob` 的 IAM 用户删除 ID 为 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` 的签名证书。**  

```
Remove-IAMSigningCertificate -UserName Bob -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMUser`
<a name="iam_DeleteUser_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMUser`。

**适用于 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 参考 (V* 5) [DeleteUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMUserFromGroup`
<a name="iam_RemoveUserFromGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMUserFromGroup`。

**适用于 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 参考 (V* 5) [RemoveUserFromGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMUserPermissionsBoundary`
<a name="iam_DeleteUserPermissionsBoundary_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMUserPermissionsBoundary`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例展示了如何删除附加到 IAM 用户的权限边界。**  

```
Remove-IAMUserPermissionsBoundary -UserName joe
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMUserPolicy`
<a name="iam_DeleteUserPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMUserPolicy`。

**适用于 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 参考 (V* 5) [DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMUserTag`
<a name="iam_UntagUser_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMUserTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从名为“joe”的用户中删除标签键为“abac”和“xyzw”的标签。要删除多个标签，请提供以逗号分隔的标签键列表。**  

```
Remove-IAMUserTag -UserName joe -TagKey "abac","xyzw"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UntagUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-IAMVirtualMFADevice`
<a name="iam_DeleteVirtualMfaDevice_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-IAMVirtualMFADevice`。

**适用于 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 参考 (V* 5) [DeleteVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Request-IAMCredentialReport`
<a name="iam_GenerateCredentialReport_powershell_topic"></a>

以下代码示例演示了如何使用 `Request-IAMCredentialReport`。

**适用于 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 参考 (V* 5) [GenerateCredentialReport](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Request-IAMServiceLastAccessedDetail`
<a name="iam_GenerateServiceLastAccessedDetails_powershell_topic"></a>

以下代码示例演示了如何使用 `Request-IAMServiceLastAccessedDetail`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例等同于 API 的 cmdlet。 GenerateServiceLastAccessedDetails 这提供了一个任务 ID，可以在 Get-IAMServiceLastAccessedDetail 和 Get-中使用 IAMService LastAccessedDetailWithEntity**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GenerateServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-IAMDefaultPolicyVersion`
<a name="iam_SetDefaultPolicyVersion_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-IAMDefaultPolicyVersion`。

**适用于 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 参考 (V* 5) [SetDefaultPolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-IAMRolePermissionsBoundary`
<a name="iam_PutRolePermissionsBoundary_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-IAMRolePermissionsBoundary`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例展示如何设置 IAM 角色的权限边界。您可以将 AWS 托管策略或自定义策略设置为权限边界。**  

```
Set-IAMRolePermissionsBoundary -RoleName MyRoleName -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-IAMUserPermissionsBoundary`
<a name="iam_PutUserPermissionsBoundary_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-IAMUserPermissionsBoundary`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例展示如何设置用户的权限边界。您可以将 AWS 托管策略或自定义策略设置为权限边界。**  

```
Set-IAMUserPermissionsBoundary -UserName joe -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Sync-IAMMFADevice`
<a name="iam_ResyncMfaDevice_powershell_topic"></a>

以下代码示例演示了如何使用 `Sync-IAMMFADevice`。

**适用于 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 参考 (V* 5) [ResyncMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-IAMGroupPolicy`
<a name="iam_DetachGroupPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-IAMGroupPolicy`。

**适用于 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 参考 (V* 5) [DetachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-IAMRolePolicy`
<a name="iam_DetachRolePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-IAMRolePolicy`。

**适用于 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 参考 (V* 5) [DetachRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-IAMUserPolicy`
<a name="iam_DetachUserPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-IAMUserPolicy`。

**适用于 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 参考 (V* 5) [DetachUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMAccessKey`
<a name="iam_UpdateAccessKey_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMAccessKey`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将名为 `Bob` 的 IAM 用户的访问密钥 `AKIAIOSFODNN7EXAMPLE` 状态更改为 `Inactive`。**  

```
Update-IAMAccessKey -UserName Bob -AccessKeyId AKIAIOSFODNN7EXAMPLE -Status Inactive
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMAccountPasswordPolicy`
<a name="iam_UpdateAccountPasswordPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMAccountPasswordPolicy`。

**适用于 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 参考 (V* 5) [UpdateAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMAssumeRolePolicy`
<a name="iam_UpdateAssumeRolePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMAssumeRolePolicy`。

**适用于 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 参考 (V* 5) [UpdateAssumeRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMGroup`
<a name="iam_UpdateGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMGroup`。

**适用于 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 参考 (V* 5) [UpdateGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMLoginProfile`
<a name="iam_UpdateLoginProfile_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMLoginProfile`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为 IAM 用户 `Bob` 设置了一个新的临时密码，并要求该用户在下次登录时更改密码。**  

```
Update-IAMLoginProfile -UserName Bob -Password "P@ssw0rd1234" -PasswordResetRequired $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMOpenIDConnectProviderThumbprint`
<a name="iam_UpdateOpenIdConnectProviderThumbprint_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMOpenIDConnectProviderThumbprint`。

**适用于 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 参考 (V* 5) [UpdateOpenIdConnectProviderThumbprint](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMRole`
<a name="iam_UpdateRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMRole`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新了角色描述和可以请求的角色会话的最长会话持续时间值（以秒为单位）。**  

```
Update-IAMRole -RoleName MyRoleName -Description "My testing role" -MaxSessionDuration 43200
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMRoleDescription`
<a name="iam_UpdateRoleDescription_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMRoleDescription`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新了您账户中 IAM 角色的描述。**  

```
Update-IAMRoleDescription -RoleName MyRoleName -Description "My testing role"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateRoleDescription](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMSAMLProvider`
<a name="iam_UpdateSamlProvider_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMSAMLProvider`。

**适用于 PowerShell V5 的工具**  
**示例 1 ：此示例使用文件 `SAMLMetaData.xml` 中的新 SAML 元数据文档更新 ARN 为 `arn:aws:iam::123456789012:saml-provider/SAMLADFS` 的 IAM 中的 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 参考 (V* 5) [UpdateSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMServerCertificate`
<a name="iam_UpdateServerCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMServerCertificate`。

**适用于 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 参考 (V* 5) [UpdateServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMSigningCertificate`
<a name="iam_UpdateSigningCertificate_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMSigningCertificate`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新了与名为 `Bob` 且其证书 ID 为 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` 的 IAM 用户关联的证书，以将其标记为非活动状态。**  

```
Update-IAMSigningCertificate -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU -UserName Bob -Status Inactive
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-IAMUser`
<a name="iam_UpdateUser_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-IAMUser`。

**适用于 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 参考 (V* 5) [UpdateUser](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-IAMGroupPolicy`
<a name="iam_PutGroupPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-IAMGroupPolicy`。

**适用于 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 参考 (V* 5) [PutGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-IAMRolePolicy`
<a name="iam_PutRolePolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-IAMRolePolicy`。

**适用于 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 参考 (V* 5) [PutRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-IAMUserPolicy`
<a name="iam_PutUserPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-IAMUserPolicy`。

**适用于 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 参考 (V* 5) [PutUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 V5 的工具的 Kinesis 示例 PowerShell
<a name="powershell_kinesis_code_examples"></a>

以下代码示例向您展示了如何使用带有 Kinesis 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-KINRecord`
<a name="kinesis_GetRecords_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-KINRecord`。

**适用于 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 参考 (V* 5) [GetRecords](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-KINShardIterator`
<a name="kinesis_GetShardIterator_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-KINShardIterator`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定分片和起始位置的分片迭代器。通过引用返回的流对象的 Shards 集合，可以从 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 参考 (V* 5) [GetShardIterator](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-KINStream`
<a name="kinesis_DescribeStream_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-KINStream`。

**适用于 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 参考 (V* 5) [DescribeStream](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-KINStream`
<a name="kinesis_CreateStream_powershell_topic"></a>

以下代码示例演示了如何使用 `New-KINStream`。

**适用于 PowerShell V5 的工具**  
**示例 1：创建新流。**  

```
New-KINStream -StreamName "mystream" -ShardCount 1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateStream](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-KINStream`
<a name="kinesis_DeleteStream_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-KINStream`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的流。在命令执行之前，系统会提示您进行确认。要取消确认提示，请使用 -Force 开关。**  

```
Remove-KINStream -StreamName "mystream"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteStream](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-KINRecord`
<a name="kinesis_PutRecord_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-KINRecord`。

**适用于 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 参考 (V* 5) [PutRecord](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 V5 的工具的 Lambda 示例 PowerShell
<a name="powershell_lambda_code_examples"></a>

以下代码示例向您展示了如何使用带有 Lambda 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-LMResourceTag`
<a name="lambda_TagResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-LMResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例将三个标签（Washington、Oregon 和 California）及其关联值添加到了由函数 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 参考 (V* 5) [TagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMAccountSetting`
<a name="lambda_GetAccountSettings_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMAccountSetting`。

**适用于 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 参考 (V* 5) [GetAccountSettings](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMAlias`
<a name="lambda_GetAlias_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMAlias`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例检索了特定 Lambda 函数别名的路由配置权重。**  

```
Get-LMAlias -FunctionName "MylambdaFunction123" -Name "newlabel1" -Select RoutingConfig
```
**输出**：  

```
AdditionalVersionWeights
------------------------
{[1, 0.6]}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetAlias](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMFunctionConcurrency`
<a name="lambda_GetFunctionConcurrency_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMFunctionConcurrency`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例获取了 Lambda 函数的预留并发**  

```
Get-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -Select *
```
**输出**：  

```
ReservedConcurrentExecutions
----------------------------
100
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMFunctionConfiguration`
<a name="lambda_GetFunctionConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMFunctionConfiguration`。

**适用于 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 参考 (V* 5) [GetFunctionConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMFunctionList`
<a name="lambda_ListFunctions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMFunctionList`。

**适用于 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 参考 (V* 5) [ListFunctions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMPolicy`
<a name="lambda_GetPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMPolicy`。

**适用于 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 参考 (V* 5) [GetPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMProvisionedConcurrencyConfig`
<a name="lambda_GetProvisionedConcurrencyConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMProvisionedConcurrencyConfig`。

**适用于 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 参考 (V* 5) [GetProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMProvisionedConcurrencyConfigList`
<a name="lambda_ListProvisionedConcurrencyConfigs_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMProvisionedConcurrencyConfigList`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例检索了 Lambda 函数的预置并发配置列表。**  

```
Get-LMProvisionedConcurrencyConfigList -FunctionName "MylambdaFunction123"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListProvisionedConcurrencyConfigs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMResourceTag`
<a name="lambda_ListTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMResourceTag`。

**适用于 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 参考 (V* 5) [ListTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-LMVersionsByFunction`
<a name="lambda_ListVersionsByFunction_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-LMVersionsByFunction`。

**适用于 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 参考 (V* 5) [ListVersionsByFunction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-LMAlias`
<a name="lambda_CreateAlias_powershell_topic"></a>

以下代码示例演示了如何使用 `New-LMAlias`。

**适用于 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 参考 (V* 5) [CreateAlias](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Publish-LMFunction`
<a name="lambda_CreateFunction_powershell_topic"></a>

以下代码示例演示了如何使用 `Publish-LMFunction`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建了一个以 MyFunction Lambda 命名的新 C\$1（d AWS otnetcore1.0 运行时）函数，从本地文件系统上的 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 参考 (V* 5) [CreateFunction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Publish-LMVersion`
<a name="lambda_PublishVersion_powershell_topic"></a>

以下代码示例演示了如何使用 `Publish-LMVersion`。

**适用于 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 参考 (V* 5) [PublishVersion](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-LMAlias`
<a name="lambda_DeleteAlias_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-LMAlias`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了命令中提到的 Lambda 函数别名。**  

```
Remove-LMAlias -FunctionName "MylambdaFunction123" -Name "NewAlias"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteAlias](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-LMFunction`
<a name="lambda_DeleteFunction_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-LMFunction`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了特定版本的 Lambda 函数**  

```
Remove-LMFunction -FunctionName "MylambdaFunction123" -Qualifier '3'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteFunction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-LMFunctionConcurrency`
<a name="lambda_DeleteFunctionConcurrency_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-LMFunctionConcurrency`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了 Lambda 函数的函数并发。**  

```
Remove-LMFunctionConcurrency -FunctionName "MylambdaFunction123"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-LMPermission`
<a name="lambda_RemovePermission_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-LMPermission`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了 Lambda 函数中指定的 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 参考 (V* 5) [RemovePermission](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-LMProvisionedConcurrencyConfig`
<a name="lambda_DeleteProvisionedConcurrencyConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-LMProvisionedConcurrencyConfig`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了特定别名的预置并发配置。**  

```
Remove-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-LMResourceTag`
<a name="lambda_UntagResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-LMResourceTag`。

**适用于 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 参考 (V* 5) [UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-LMAlias`
<a name="lambda_UpdateAlias_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-LMAlias`。

**适用于 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 参考 (V* 5) [UpdateAlias](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-LMFunctionCode`
<a name="lambda_UpdateFunctionCode_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-LMFunctionCode`。

**适用于 PowerShell V5 的工具**  
**示例 1：使用指定 zip 文件中包含的新内容更新名为 MyFunction “” 的函数。对于 C\$1 .NET 核心 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 参考 (V* 5) [UpdateFunctionCode](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-LMFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-LMFunctionConfiguration`。

**适用于 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 参考 (V* 5) [UpdateFunctionConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-LMFunctionConcurrency`
<a name="lambda_PutFunctionConcurrency_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-LMFunctionConcurrency`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例将函数的并发设置作为一个整体应用。**  

```
Write-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -ReservedConcurrentExecution 100
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-LMProvisionedConcurrencyConfig`
<a name="lambda_PutProvisionedConcurrencyConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-LMProvisionedConcurrencyConfig`。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例将预置并发配置添加到了函数的别名**  

```
Write-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -ProvisionedConcurrentExecution 20 -Qualifier "NewAlias1"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Amazon 机器学习示例
<a name="powershell_machine-learning_code_examples"></a>

以下代码示例向您展示如何使用带有 Amazon ML 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-MLBatchPrediction`
<a name="machine-learning_GetBatchPrediction_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLBatchPrediction`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 id 为 ID 的批量预测的详细元数据。**  

```
Get-MLBatchPrediction -BatchPredictionId ID
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBatchPrediction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-MLBatchPredictionList`
<a name="machine-learning_DescribeBatchPredictions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLBatchPredictionList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 BatchPredictions 与请求中给出的搜索条件相匹配的所有数据记录及其关联数据记录的列表。**  

```
Get-MLBatchPredictionList
```
**示例 2：返回状态为 “已完成” 的所有 BatchPredictions 内容的列表。**  

```
Get-MLBatchPredictionList -FilterVariable Status -EQ COMPLETED
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeBatchPredictions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-MLDataSource`
<a name="machine-learning_GetDataSource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLDataSource`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 ID 为 ID 的 a DataSource 的元数据、状态和数据文件信息**  

```
Get-MLDataSource -DataSourceId ID
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetDataSource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-MLDataSourceList`
<a name="machine-learning_DescribeDataSources_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLDataSourceList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回所有数据记录 DataSources 及其关联数据记录的列表。**  

```
Get-MLDataSourceList
```
**示例 2：返回状态为 “已完成” 的所有 DataSources 内容的列表。**  

```
Get-MLDataDourceList -FilterVariable Status -EQ COMPLETED
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeDataSources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-MLEvaluation`
<a name="machine-learning_GetEvaluation_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLEvaluation`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 id 为 ID 的 Evaluation 的元数据和状态。**  

```
Get-MLEvaluation -EvaluationId ID
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetEvaluation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-MLEvaluationList`
<a name="machine-learning_DescribeEvaluations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLEvaluationList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回所有 Evaluation 资源的列表**  

```
Get-MLEvaluationList
```
**示例 2：返回状态为 COMPLETED 的所有 Evaulation 的列表。**  

```
Get-MLEvaluationList -FilterVariable Status -EQ COMPLETED
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeEvaluations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-MLModel`
<a name="machine-learning_GetMLModel_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLModel`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 ID 为 ID 的详细元数据、状态、架构和数据文件信息。 MLModel **  

```
Get-MLModel -ModelId ID
```
+  有关 API 的详细信息，请参阅 [Get MLModel in AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/v5/reference) *Cmdlet 参考 (V5)*。

### `Get-MLModelList`
<a name="machine-learning_DescribeMLModels_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLModelList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回所有 Model 及其关联数据记录的列表。**  

```
Get-MLModelList
```
**示例 2：返回状态为 COMPLETED 的所有 Model 的列表。**  

```
Get-MLModelList -FilterVariable Status -EQ COMPLETED
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考文档 (V* 5) MLModels 中的[描述](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-MLPrediction`
<a name="machine-learning_Predict_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MLPrediction`。

**适用于 PowerShell V5 的工具**  
**示例 1：向 id 为 ID 的模型的实时预测端点 URL 发送一条记录。**  

```
Get-MLPrediction -ModelId ID -PredictEndpoint URL -Record @{"A" = "B"; "C" = "D";}
```
+  有关 API 详细信息，请参阅《AWS Tools for PowerShell Cmdlet Reference (V5)》**中的 [Predict](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLBatchPrediction`
<a name="machine-learning_CreateBatchPrediction_powershell_topic"></a>

以下代码示例演示了如何使用 `New-MLBatchPrediction`。

**适用于 PowerShell V5 的工具**  
**示例 1：为 id 为 ID 的模型创建新的批量预测请求，并将输出放在指定的 S3 位置。**  

```
New-MLBatchPrediction -ModelId ID -Name NAME -OutputURI s3://...
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateBatchPrediction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-MLDataSourceFromS3`
<a name="machine-learning_CreateDataSourceFromS3_powershell_topic"></a>

以下代码示例演示了如何使用 `New-MLDataSourceFromS3`。

**适用于 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 参考 (V* 5) [CreateDataSourceFrom中的 S3](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLEvaluation`
<a name="machine-learning_CreateEvaluation_powershell_topic"></a>

以下代码示例演示了如何使用 `New-MLEvaluation`。

**适用于 PowerShell V5 的工具**  
**示例 1：为给定的数据来源 ID 和模型 ID 创建评估**  

```
New-MLEvaluation -Name NAME -DataSourceId DSID -ModelId MID
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateEvaluation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-MLModel`
<a name="machine-learning_CreateMLModel_powershell_topic"></a>

以下代码示例演示了如何使用 `New-MLModel`。

**适用于 PowerShell V5 的工具**  
**示例 1：使用训练数据创建新模型。**  

```
New-MLModel -Name NAME -ModelType BINARY -Parameter @{...} -TrainingDataSourceId ID
```
+  有关 API 的详细信息，请参阅MLModel在 *AWS Tools for PowerShell Cmdlet 参考文档 (V* 5) 中[创建](https://docs.aws.amazon.com/powershell/v5/reference)。

### `New-MLRealtimeEndpoint`
<a name="machine-learning_CreateRealtimeEndpoint_powershell_topic"></a>

以下代码示例演示了如何使用 `New-MLRealtimeEndpoint`。

**适用于 PowerShell V5 的工具**  
**示例 1：为给定模型 ID 创建新的实时预测端点。**  

```
New-MLRealtimeEndpoint -ModelId ID
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateRealtimeEndpoint](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用 V5 版工具的 Macie 示例 PowerShell
<a name="powershell_macie2_code_examples"></a>

以下代码示例向您展示了如何使用带有 Macie 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-MAC2FindingList`
<a name="macie2_ListFindings_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-MAC2FindingList`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回包含敏感数据检测结果的 FindingIds 列表，类型为 “CREDIT\$1CARD\$1NUMBER” 或 “US\$1SOCIAL\$1SECURITY\$1NUMBER”**  

```
$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 参考 (V* 5) [ListFindings](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS 价目表 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_pricing_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS 价目表的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-PLSAttributeValue`
<a name="pricing_GetAttributeValues_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-PLSAttributeValue`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 us-east-1 区域的亚马逊属性 “VolumeType” EC2 的值。**  

```
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 参考 (V* 5) [GetAttributeValues](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-PLSProduct`
<a name="pricing_GetProducts_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-PLSProduct`。

**适用于 PowerShell V5 的工具**  
**示例 1：亚马逊所有商品的退货详情 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：返回亚马逊 EC2 在 us-east-1 地区的数据，这些数据按支持 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 参考 (V* 5) [GetProducts](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-PLSService`
<a name="pricing_DescribeServices_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-PLSService`。

**适用于 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 EC2 区域中亚马逊服务的元数据。**  

```
Get-PLSService -ServiceCode AmazonEC2 -Region us-east-1
```
**输出**：  

```
AttributeNames                                                         ServiceCode
--------------                                                         -----------
{volumeType, maxIopsvolume, instanceCapacity10xlarge, locationType...} AmazonEC2
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Resource Groups 示例
<a name="powershell_resource-groups_code_examples"></a>

以下代码示例向您展示了如何使用带有 Resource Groups 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-RGResourceTag`
<a name="resource-groups_Tag_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-RGResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例向指定的资源组 arn 添加标签键“Instances”，其值为“workboxes”**  

```
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 Reference (V5)》**中的 [Tag](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Find-RGResource`
<a name="resource-groups_SearchResources_powershell_topic"></a>

以下代码示例演示了如何使用 `Find-RGResource`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用标签筛选器 ResourceQuery 创建 for Instance 资源类型并查找资源。**  

```
$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 参考 (V* 5) [SearchResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGGroup`
<a name="resource-groups_GetGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGGroup`。

**适用于 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 参考 (V* 5) [GetGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGGroupList`
<a name="resource-groups_ListGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGGroupList`。

**适用于 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 参考 (V* 5) [ListGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGGroupQuery`
<a name="resource-groups_GetGroupQuery_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGGroupQuery`。

**适用于 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 参考 (V* 5) [GetGroupQuery](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGGroupResourceList`
<a name="resource-groups_ListGroupResources_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGGroupResourceList`。

**适用于 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 参考 (V* 5) [ListGroupResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGResourceTag`
<a name="resource-groups_GetTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGResourceTag`。

**适用于 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 参考 (V* 5) [GetTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-RGGroup`
<a name="resource-groups_CreateGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-RGGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建了一个名 TestPowerShellGroup为的基于标签的新资源组 Resource Groups AWS 资源组。该组包括当前区域中使用标签键 “名称” 和标签值 “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 参考 (V* 5) [CreateGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-RGGroup`
<a name="resource-groups_DeleteGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-RGGroup`。

**适用于 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 参考 (V* 5) [DeleteGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-RGResourceTag`
<a name="resource-groups_Untag_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-RGResourceTag`。

**适用于 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 Reference (V5)》**中的 [Untag](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-RGGroup`
<a name="resource-groups_UpdateGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-RGGroup`。

**适用于 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 参考 (V* 5) [UpdateGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-RGGroupQuery`
<a name="resource-groups_UpdateGroupQuery_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-RGGroupQuery`。

**适用于 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 参考 (V* 5) [UpdateGroupQuery](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# Resource Groups 使用适用于 V5 的 PowerShell 工具标记 API 示例
<a name="powershell_resource-groups-tagging-api_code_examples"></a>

以下代码示例向您展示了如何使用带有 Resource Groups Tagging API 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-RGTResourceTag`
<a name="resource-groups-tagging-api_TagResources_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-RGTResourceTag`。

**适用于 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 表中。对该服务进行了两次调用，即对于通过管道传入 cmdlet 的每个资源 ARN 进行一次调用。**  

```
$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 参考 (V* 5) [TagResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGTResource`
<a name="resource-groups-tagging-api_GetResources_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGTResource`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回某个区域中所有带标签的资源及与资源关联的标签键。如果没有向 cmdlet 提供-Region 参数，它将尝试从 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 资源名称（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 参考 (V* 5) [GetResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGTTagKey`
<a name="resource-groups-tagging-api_GetTagKeys_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGTTagKey`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定区域中的所有标签键。如果未指定-Region 参数，cmdlet 将尝试从默认外壳区域或实例元数据中推断出该区域。 EC2 请注意，标签键不会按任何特定顺序返回。**  

```
Get-RGTTagKey -region us-west-2
```
**输出**：  

```
version
stage
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetTagKeys](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-RGTTagValue`
<a name="resource-groups-tagging-api_GetTagValues_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-RGTTagValue`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回某个区域中指定标签的值。如果未指定-Region 参数，cmdlet 将尝试从默认外壳区域或实例元数据中推断出该区域。 EC2 **  

```
Get-RGTTagValue -Key "stage" -Region us-west-2
```
**输出**：  

```
beta
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetTagValues](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-RGTResourceTag`
<a name="resource-groups-tagging-api_UntagResources_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-RGTResourceTag`。

**适用于 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”以及关联的值。对该服务进行了两次调用，即对于通过管道传入 cmdlet 的每个资源 ARN 进行一次调用。每次调用之前，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 参考 (V* 5) [UntagResources](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用 PowerShell V5 工具的 Route 53 示例
<a name="powershell_route-53_code_examples"></a>

以下代码示例向您展示了如何使用带有 Route 53 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Edit-R53ResourceRecordSet`
<a name="route-53_ChangeResourceRecordSets_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-R53ResourceRecordSet`。

**适用于 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的示例，'-1111111111.us-east example-load-balancer -1.elb.amazonaws.com'是负载均衡器域名的示例，亚马逊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 将两个加权别名资源记录集彼此区分开来。此元素是必需的，因为两个资源记录集的“名称”和“类型”元素具有相同的值。Z1111111111111 和 Z3333333333333 是 ELB 负载均衡器的托管区域的示例，值 IDs 为指定。 DNSName example-load-balancer-2222222222.us-east-1.elb.amazonaws.com 和- example-load-balancer 44444444444.us-east-1.elb.amazonaws.com 是亚马逊 Route 53 回复 example.com 查询的 Elastic Load Balancing 域名的示例。有关更多详细信息，请参阅 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 参考 (V* 5) [ChangeResourceRecordSets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53AccountLimit`
<a name="route-53_GetAccountLimit_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53AccountLimit`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回可以使用当前账户创建的托管区的最大数量。**  

```
Get-R53AccountLimit -Type MAX_HOSTED_ZONES_BY_OWNER
```
**输出**：  

```
15
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetAccountLimit](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53CheckerIpRanges`
<a name="route-53_GetCheckerIpRanges_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53CheckerIpRanges`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回 Route53 运行状况检查器的 CIDRs **  

```
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 参考 (V* 5) [GetCheckerIpRanges](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53HostedZone`
<a name="route-53_GetHostedZone_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53HostedZone`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 ID 为 Z1D633 的托管区域的详细信息PJN98FT9。**  

```
Get-R53HostedZone -Id Z1D633PJN98FT9
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53HostedZoneCount`
<a name="route-53_GetHostedZoneCount_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53HostedZoneCount`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回当前的公有和私有托管区域的总数 AWS 账户。**  

```
Get-R53HostedZoneCount
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetHostedZoneCount](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53HostedZoneLimit`
<a name="route-53_GetHostedZoneLimit_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53HostedZoneLimit`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回对可在指定托管区中创建的最大记录数的限制。**  

```
Get-R53HostedZoneLimit -HostedZoneId Z3MEQ8T7HAAAAF -Type MAX_RRSETS_BY_ZONE
```
**输出**：  

```
5
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetHostedZoneLimit](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53HostedZoneList`
<a name="route-53_ListHostedZones_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53HostedZoneList`。

**适用于 PowerShell V5 的工具**  
**示例 1：输出所有公有和私有托管区。**  

```
Get-R53HostedZoneList
```
**示例 2：输出与 ID 为 NZ8 X2CISAMPLE 的可重复使用的委托集关联的所有托管区域**  

```
Get-R53HostedZoneList -DelegationSetId NZ8X2CISAMPLE
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListHostedZones](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53HostedZonesByName`
<a name="route-53_ListHostedZonesByName_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53HostedZonesByName`。

**适用于 PowerShell V5 的工具**  
**示例 1：按照域名以 ASCII 顺序返回所有公有和私有托管区。**  

```
Get-R53HostedZonesByName
```
**示例 2：按照域名以 ASCII 顺序返回公有和私有托管区，开头为指定的 DNS 名称。**  

```
Get-R53HostedZonesByName -DnsName example2.com
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListHostedZonesByName](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53QueryLoggingConfigList`
<a name="route-53_ListQueryLoggingConfigs_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53QueryLoggingConfigList`。

**适用于 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 参考 (V* 5) [ListQueryLoggingConfigs](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-R53ReusableDelegationSet`
<a name="route-53_GetReusableDelegationSet_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-R53ReusableDelegationSet`。

**适用于 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 参考 (V* 5) [GetReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-R53HostedZone`
<a name="route-53_CreateHostedZone_powershell_topic"></a>

以下代码示例演示了如何使用 `New-R53HostedZone`。

**适用于 PowerShell V5 的工具**  
**示例 1：创建名为“example.com”的新托管区，并与可重复使用的委托集相关联。请注意，您必须为 CallerReference 参数提供一个值，这样在必要时需要重试的请求就不会有执行两次操作的风险。由于托管区域是在 VPC 中创建的，因此它自动为私有区域，因此您不应设置-HostedZoneConfig \$1 PrivateZone 参数。**  

```
$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 参考 (V* 5) [CreateHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-R53QueryLoggingConfig`
<a name="route-53_CreateQueryLoggingConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `New-R53QueryLoggingConfig`。

**适用于 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 参考 (V* 5) [CreateQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-R53ReusableDelegationSet`
<a name="route-53_CreateReusableDelegationSet_powershell_topic"></a>

以下代码示例演示了如何使用 `New-R53ReusableDelegationSet`。

**适用于 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 参考 (V* 5) [CreateReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-R53VPCWithHostedZone`
<a name="route-53_AssociateVPCWithHostedZone_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-R53VPCWithHostedZone`。

**适用于 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 参考文档 (V* 5) VPCWith HostedZone 中的[关联](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-R53HostedZone`
<a name="route-53_DeleteHostedZone_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-R53HostedZone`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除具有指定 ID 的托管区。在命令继续之前，您将收到进行确认的提示，除非您添加了 -Force 开关参数。**  

```
Remove-R53HostedZone -Id Z1PA6795UKMFR9
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-R53QueryLoggingConfig`
<a name="route-53_DeleteQueryLoggingConfig_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-R53QueryLoggingConfig`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例移除指定 DNS 查询日志记录的指定配置。**  

```
Remove-R53QueryLoggingConfig -Id ee528e95-4e03-4fdc-9d28-9e24daaa20063
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-R53ReusableDelegationSet`
<a name="route-53_DeleteReusableDelegationSet_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-R53ReusableDelegationSet`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定的可重用委派集。**  

```
Remove-R53ReusableDelegationSet -Id N23DS9X4AYAAAM
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-R53VPCFromHostedZone`
<a name="route-53_DisassociateVPCFromHostedZone_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-R53VPCFromHostedZone`。

**适用于 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) VPCFrom HostedZone 中的[取消关联](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Update-R53HostedZoneComment`
<a name="route-53_UpdateHostedZoneComment_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-R53HostedZoneComment`。

**适用于 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 参考 (V* 5) [UpdateHostedZoneComment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Amazon S3 示例
<a name="powershell_s3_code_examples"></a>

以下代码示例向您展示了如何通过将 AWS Tools for PowerShell V5 与 Amazon S3 配合使用来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Copy-S3Object`
<a name="s3_CopyObject_powershell_topic"></a>

以下代码示例演示了如何使用 `Copy-S3Object`。

**适用于 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 参考 (V* 5) [CopyObject](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3Bucket`
<a name="s3_ListBuckets_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3Bucket`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回所有 S3 存储桶。**  

```
Get-S3Bucket
```
**示例 2：此命令返回名为“test-files”的存储桶**  

```
Get-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListBuckets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketACL`
<a name="s3_GetBucketAcl_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketACL`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令获取 S3 对象的对象所有者的详细信息。**  

```
(Get-S3BucketACL -BucketName 'amzn-s3-demo-bucket' -Select *).Owner
```
**输出**：  

```
DisplayName Id
----------- --
testusername      9988776a6554433d22f1100112e334acb45566778899009e9887bd7f66c5f544
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketAcl](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketAccelerateConfiguration`
<a name="s3_GetBucketAccelerateConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketAccelerateConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：如果为指定的存储桶启用了传输加速设置，则此命令将返回值 Enabled。**  

```
Get-S3BucketAccelerateConfiguration -BucketName 'amzn-s3-demo-bucket'
```
**输出**：  

```
Value                                  
-----                                    
Enabled
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketAnalyticsConfiguration`
<a name="s3_GetBucketAnalyticsConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketAnalyticsConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回给定 S3 存储桶中名为“testfilter”的分析筛选条件的详细信息。**  

```
Get-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketAnalyticsConfigurationList`
<a name="s3_ListBucketAnalyticsConfigurations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketAnalyticsConfigurationList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回给定 S3 存储桶的前 100 个分析配置。**  

```
Get-S3BucketAnalyticsConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListBucketAnalyticsConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketEncryption`
<a name="s3_GetBucketEncryption_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketEncryption`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回与给定存储桶关联的所有服务器端加密规则。**  

```
Get-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketInventoryConfiguration`
<a name="s3_GetBucketInventoryConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketInventoryConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回给定 S3 存储桶的名为“testinventory”的清单的详细信息。**  

```
Get-S3BucketInventoryConfiguration -BucketName 'amzn-s3-demo-bucket' -InventoryId 'testinventory'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketInventoryConfigurationList`
<a name="s3_ListBucketInventoryConfigurations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketInventoryConfigurationList`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回给定 S3 存储桶的前 100 个清单配置。**  

```
Get-S3BucketInventoryConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListBucketInventoryConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketLocation`
<a name="s3_GetBucketLocation_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketLocation`。

**适用于 PowerShell V5 的工具**  
**示例 1：如果存在约束，则此命令返回存储桶“amzn-s3-demo-bucket”的位置约束。**  

```
Get-S3BucketLocation -BucketName 'amzn-s3-demo-bucket'
```
**输出**：  

```
Value
-----
ap-south-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketLocation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketLogging`
<a name="s3_GetBucketLogging_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketLogging`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回指定存储桶的日志记录状态。**  

```
Get-S3BucketLogging -BucketName 'amzn-s3-demo-bucket'
```
**输出**：  

```
TargetBucketName   Grants TargetPrefix
----------------   ------ ------------
testbucket1        {}     testprefix
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketLogging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketMetricsConfiguration`
<a name="s3_GetBucketMetricsConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketMetricsConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回有关给定 S3 存储桶的名为“testfilter”的指标筛选条件的详细信息。**  

```
Get-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testfilter'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketNotification`
<a name="s3_GetBucketNotification_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketNotification`。

**适用于 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 参考 (V* 5) [GetBucketNotification](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketPolicy`
<a name="s3_GetBucketPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令输出与给定 S3 存储桶关联的存储桶策略。**  

```
Get-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketPolicyStatus`
<a name="s3_GetBucketPolicyStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketPolicyStatus`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回给定 S3 存储桶的策略状态，此状态指示存储桶是否为公有存储桶。**  

```
Get-S3BucketPolicyStatus -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketPolicyStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketReplication`
<a name="s3_GetBucketReplication_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketReplication`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回在名为“amzn-s3-demo-bucket”的存储桶上设置的复制配置信息。**  

```
Get-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketRequestPayment`
<a name="s3_GetBucketRequestPayment_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketRequestPayment`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回名为“amzn-s3-demo-bucket”的存储桶的请求付款配置。默认情况下，存储桶拥有者支付从存储桶进行下载的费用。**  

```
Get-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketRequestPayment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketTagging`
<a name="s3_GetBucketTagging_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketTagging`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回与给定存储桶关联的所有标签。**  

```
Get-S3BucketTagging -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketVersioning`
<a name="s3_GetBucketVersioning_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketVersioning`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回与给定存储桶相关的版本控制状态。**  

```
Get-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketVersioning](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3BucketWebsite`
<a name="s3_GetBucketWebsite_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3BucketWebsite`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回给定 S3 存储桶的静态网站配置的详细信息。**  

```
Get-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3CORSConfiguration`
<a name="s3_GetCORSConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3CORSConfiguration`。

**适用于 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 的详细信息，请参阅 [Get CORSConfiguration in AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/v5/reference) *Cmdlet 参考 (V5)*。

### `Get-S3HeadBucket`
<a name="s3_HeadBucket_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3HeadBucket`。

**适用于 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： NotFound 对于不存在的存储桶，此命令会引发错误，并显示 HTTP 状态代码。**  

```
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 参考 (V* 5) [HeadBucket](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3LifecycleConfiguration`
<a name="s3_GetLifecycleConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3LifecycleConfiguration`。

**适用于 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 参考 (V* 5) [GetLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3Object`
<a name="s3_ListObjects_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3Object`。

**适用于 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 参考 (V* 5) [ListObjects](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3ObjectACL`
<a name="s3_GetObjectAcl_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3ObjectACL`。

**适用于 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 参考 (V* 5) [GetObjectAcl](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3ObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3ObjectLockConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：如果为给定的 S3 存储桶启用了对象锁定配置，则此命令将返回值“Enabled”。**  

```
Get-S3ObjectLockConfiguration -BucketName 'amzn-s3-demo-bucket' -Select ObjectLockConfiguration.ObjectLockEnabled
```
**输出**：  

```
Value
-----
Enabled
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetObjectLockConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3ObjectMetadata`
<a name="s3_GetObjectMetadata_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3ObjectMetadata`。

**适用于 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 参考 (V* 5) [GetObjectMetadata](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3ObjectRetention`
<a name="s3_GetObjectRetention_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3ObjectRetention`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令返回保留对象之前的模式和日期。**  

```
Get-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetObjectRetention](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3ObjectTagSet`
<a name="s3_GetObjectTagging_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3ObjectTagSet`。

**适用于 PowerShell V5 的工具**  
**示例 1：该示例返回与给定 S3 存储桶上存在的对象关联的标签。**  

```
Get-S3ObjectTagSet -Key 'testfile.txt' -BucketName 'amzn-s3-demo-bucket'
```
**输出**：  

```
Key  Value
---  -----
test value
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetObjectTagging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3PreSignedURL`
<a name="s3_GetPreSignedURL_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3PreSignedURL`。

**适用于 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 参考 (V* 5) 中的[GetPreSigned网址](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-S3PublicAccessBlock`
<a name="s3_GetPublicAccessBlock_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3PublicAccessBlock`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令返回给定 S3 存储桶的公共访问权限屏蔽设置。**  

```
Get-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetPublicAccessBlock](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-S3Version`
<a name="s3_ListVersions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-S3Version`。

**适用于 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 参考 (V* 5) [ListVersions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-S3Bucket`
<a name="s3_PutBucket_powershell_topic"></a>

以下代码示例演示了如何使用 `New-S3Bucket`。

**适用于 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：此命令使用创建名为 “amzn-s3-demo-bucket-use1-az5-x-s3” 的新目录存储桶。 PutBucketConfiguration**  

```
$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 参考 (V* 5) [PutBucket](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Read-S3Object`
<a name="s3_GetObject_powershell_topic"></a>

以下代码示例演示了如何使用 `Read-S3Object`。

**适用于 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 参考 (V* 5) [GetObject](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3Bucket`
<a name="s3_DeleteBucket_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3Bucket`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令从存储桶“test-files”中移除所有对象和对象版本，然后删除该存储桶。在继续操作之前，该命令将提示进行确认。添加 -Force 开关可禁止确认。请注意，不能删除不为空的存储桶。**  

```
Remove-S3Bucket -BucketName amzn-s3-demo-bucket -DeleteBucketContent
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteBucket](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketAnalyticsConfiguration`
<a name="s3_DeleteBucketAnalyticsConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketAnalyticsConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令移除给定 S3 存储桶中名为“testfilter”的分析筛选条件。**  

```
Remove-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketEncryption`
<a name="s3_DeleteBucketEncryption_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketEncryption`。

**适用于 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 参考 (V* 5) [DeleteBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketInventoryConfiguration`
<a name="s3_DeleteBucketInventoryConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketInventoryConfiguration`。

**适用于 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 参考 (V* 5) [DeleteBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketMetricsConfiguration`
<a name="s3_DeleteBucketMetricsConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketMetricsConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令移除给定 S3 存储桶中名为“testmetrics”的指标筛选条件。**  

```
Remove-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testmetrics'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketPolicy`
<a name="s3_DeleteBucketPolicy_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketPolicy`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令移除与给定 S3 存储桶关联的存储桶策略。**  

```
Remove-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteBucketPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketReplication`
<a name="s3_DeleteBucketReplication_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketReplication`。

**适用于 PowerShell V5 的工具**  
**示例 1：删除与名为“amzn-s3-demo-bucket”的存储桶关联的复制配置。请注意，此操作需要 s3: DeleteReplicationConfiguration 操作的权限。在操作继续之前，系统将提示您进行确认 - 要取消确认，请使用 -Force 开关。**  

```
Remove-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketTagging`
<a name="s3_DeleteBucketTagging_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketTagging`。

**适用于 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 参考 (V* 5) [DeleteBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3BucketWebsite`
<a name="s3_DeleteBucketWebsite_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3BucketWebsite`。

**适用于 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 参考 (V* 5) [DeleteBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3CORSConfiguration`
<a name="s3_DeleteCORSConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3CORSConfiguration`。

**适用于 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 参考文档 (V* 5) CORSConfiguration 中的[删除](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Remove-S3LifecycleConfiguration`
<a name="s3_DeleteLifecycleConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3LifecycleConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令移除给定 S3 存储桶的所有生命周期规则。**  

```
Remove-S3LifecycleConfiguration -BucketName 'amzn-s3-demo-bucket'
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3MultipartUpload`
<a name="s3_AbortMultipartUpload_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3MultipartUpload`。

**适用于 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 参考 (V* 5) [AbortMultipartUpload](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3Object`
<a name="s3_DeleteObjects_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3Object`。

**适用于 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 实例的集合，每个实例都有一个标识对象的字符串类型的 Key 成员**。  

```
Remove-S3Object -bucketname "amzn-s3-demo-bucket" -KeyCollection (Get-S3Object "test-files" -KeyPrefix "prefix/subprefix" | select -ExpandProperty Key)
```
**示例 5：此示例获取存储桶中所有具有键前缀“prefix/subprefix”的对象并将其删除。请注意，一次只能处理一个传入的对象。对于大型集合，可以考虑将集合传递给 cmdlet 的-InputObject （别名-S3ObjectCollection）参数，这样只需调用一次服务即可批量删除操作。**  

```
Get-S3Object -BucketName "amzn-s3-demo-bucket" -KeyPrefix "prefix/subprefix" | Remove-S3Object -Force
```
**示例 6：此示例将代表删除标记的 Amazon.S3.Model.S3 ObjectVersion 实例的集合传送到 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 参考 (V* 5) [DeleteObjects](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3ObjectTagSet`
<a name="s3_DeleteObjectTagging_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3ObjectTagSet`。

**适用于 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 参考 (V* 5) [DeleteObjectTagging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-S3PublicAccessBlock`
<a name="s3_DeletePublicAccessBlock_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-S3PublicAccessBlock`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令关闭给定存储桶的屏蔽公共访问权限配置。**  

```
Remove-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket' -Force -Select '^BucketName'
```
**输出**：  

```
amzn-s3-demo-bucket
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeletePublicAccessBlock](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-S3BucketEncryption`
<a name="s3_PutBucketEncryption_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-S3BucketEncryption`。

**适用于 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 参考 (V* 5) [PutBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Test-S3Bucket`
<a name="s3_Test-S3Bucket_powershell_topic"></a>

以下代码示例演示了如何使用 `Test-S3Bucket`。

**适用于 PowerShell V5 的工具**  
**示例 1：如果存储桶存在，此命令返回 True，否则返回 False。即使存储桶不属于该用户，该命令也会返回 True。**  

```
Test-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [Test-S3Bucket](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3BucketAccelerateConfiguration`
<a name="s3_PutBucketAccelerateConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3BucketAccelerateConfiguration`。

**适用于 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 参考 (V* 5) [PutBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3BucketNotification`
<a name="s3_PutBucketNotification_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3BucketNotification`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为 S3 事件配置 SNS 主题配置 ObjectRemovedDelete 并启用给定 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：此示例 ObjectCreatedAll 为给定存储桶启用通知，将其发送到 Lambda 函数。**  

```
$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 参考 (V* 5) [PutBucketNotification](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3BucketReplication`
<a name="s3_PutBucketReplication_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3BucketReplication`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用一条规则设置复制配置，允许将存储桶 “amzn-s3-demo-bucket” 中使用密钥名称前缀 “” 创建的任何新对象复制到 “amzn-s3-demo-bucket” 存储桶。TaxDocs**  

```
$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：此示例设置了具有多个规则的复制配置，允许将使用密钥名称前缀 “” 或 “” 创建的任何新对象复制到 “amzn-s3-demo-bucket” 存储桶。TaxDocs OtherDocs键前缀不得重叠。**  

```
$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：此示例更新了指定存储桶上的复制配置，以禁用控制将密钥名称前缀 “” 的对象复制到存储桶 “amzn-s3-demo-bucketTaxDocs” 的规则。**  

```
$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 参考 (V* 5) [PutBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3BucketRequestPayment`
<a name="s3_PutBucketRequestPayment_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3BucketRequestPayment`。

**适用于 PowerShell V5 的工具**  
**示例 1：更新名为“amzn-s3-demo-bucket”的存储桶的请求付款配置，以便向从该存储桶请求下载的人员收取下载费用。默认情况下，存储桶拥有者支付下载的费用。要将请求付款设置回默认值，请使用 “BucketOwner” 作为 RequestPaymentConfiguration \$1Payer 参数。**  

```
Write-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket -RequestPaymentConfiguration_Payer Requester
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutBucketRequestPayment](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3BucketTagging`
<a name="s3_PutBucketTagging_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3BucketTagging`。

**适用于 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 参考 (V* 5) [PutBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3BucketVersioning`
<a name="s3_PutBucketVersioning_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3BucketVersioning`。

**适用于 PowerShell V5 的工具**  
**示例 1：该命令为给定 S3 存储桶启用版本控制。**  

```
Write-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket' -VersioningConfig_Status Enabled
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutBucketVersioning](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3BucketWebsite`
<a name="s3_PutBucketWebsite_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3BucketWebsite`。

**适用于 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 参考 (V* 5) [PutBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3LifecycleConfiguration`
<a name="s3_PutLifecycleConfiguration_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3LifecycleConfiguration`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例写入/替换 \$1 中提供的配置NewRule。此配置确保使用给定的前缀和标签值来限制范围对象。**  

```
$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：此示例使用筛选设置了多个规则。 \$1 ArchiveRule 将对象设置为在 30 天内存档到 Glacier，120 天后存档到 Glacier DeepArchive。 对于前缀为 “py” 且标签：key “已存档” 设置为 “是” 的对象，\$1将在 150 天后过ExpireRule 期**。  

```
$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 参考 (V* 5) [PutLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3Object`
<a name="s3_PutObject_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3Object`。

**适用于 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，在存储桶 “测试文件” 中创建密钥为 “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”，其中 “文件名” 会有所不同。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder .\Scripts -KeyPrefix SampleScripts\
```
**示例 5：此命令将本地目录 “脚本” 中的所有\$1.ps1 文件上传到存储桶 “test-files”，并将公用密钥前缀 “” 应用于每个对象。SampleScripts每个上传的文件都将有一个密钥 “SampleScripts/filename.ps1”，其中 “文件名” 会有所不同。**  

```
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 参考 (V* 5) [PutObject](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-S3ObjectRetention`
<a name="s3_PutObjectRetention_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-S3ObjectRetention`。

**适用于 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 参考 (V* 5) [PutObjectRetention](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 V5 的工具的 Security Hub CSPM 示例 PowerShell
<a name="powershell_securityhub_code_examples"></a>

以下代码示例向您展示了如何使用带有 Security Hub CSPM 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-SHUBFinding`
<a name="securityhub_GetSHUBFinding_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SHUBFinding`。

**适用于 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 参考 (V* 5) [GetFindings](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Amazon SES 示例
<a name="powershell_ses_code_examples"></a>

以下代码示例向您展示如何使用带有 Amazon SES 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Get-SESIdentity`
<a name="ses_ListIdentities_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SESIdentity`。

**适用于 PowerShell V5 的工具**  
**示例 1：无论验证状态如何，此命令都会返回包含特定 AWS 账户的所有身份（电子邮件地址和域名）的列表。**  

```
Get-SESIdentity
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListIdentities](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SESSendQuota`
<a name="ses_GetSendQuota_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SESSendQuota`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回用户的当前发送限制。**  

```
Get-SESSendQuota
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetSendQuota](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SESSendStatistic`
<a name="ses_GetSendStatistics_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SESSendStatistic`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令返回用户的发送统计信息。结果是数据点的列表，表示过去两周的发送活动。列表中的每个数据点都包含 15 分钟间隔的统计信息。**  

```
Get-SESSendStatistic
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetSendStatistics](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用 PowerShell 于 V5 的工具的 Amazon SES API v2 示例
<a name="powershell_sesv2_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon SES API v2 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Send-SES2Email`
<a name="sesv2_SendSES2Email_powershell_topic"></a>

以下代码示例演示了如何使用 `Send-SES2Email`。

**适用于 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 参考 (V* 5) [SendEmail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 V5 的工具的 Amazon SNS 示例 PowerShell
<a name="powershell_sns_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon SNS 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Publish-SNSMessage`
<a name="sns_Publish_powershell_topic"></a>

以下代码示例演示了如何使用 `Publish-SNSMessage`。

**适用于 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 Reference (V5)》**中的 [Publish](https://docs.aws.amazon.com/powershell/v5/reference)。

# 使用适用于 V5 的工具的亚马逊 SQS 示例 PowerShell
<a name="powershell_sqs_code_examples"></a>

以下代码示例向您展示如何使用带有 Amazon SQS 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-SQSPermission`
<a name="sqs_AddPermission_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-SQSPermission`。

**适用于 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 参考 (V* 5) [AddPermission](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Clear-SQSQueue`
<a name="sqs_PurgeQueue_powershell_topic"></a>

以下代码示例演示了如何使用 `Clear-SQSQueue`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了指定队列中的所有消息。**  

```
Clear-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PurgeQueue](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-SQSMessageVisibility`
<a name="sqs_ChangeMessageVisibility_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-SQSMessageVisibility`。

**适用于 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 参考 (V* 5) [ChangeMessageVisibility](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-SQSMessageVisibilityBatch`
<a name="sqs_ChangeMessageVisibilityBatch_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-SQSMessageVisibilityBatch`。

**适用于 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 参考 (V* 5) [ChangeMessageVisibilityBatch](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SQSDeadLetterSourceQueue`
<a name="sqs_ListDeadLetterSourceQueues_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SQSDeadLetterSourceQueue`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列 URLs 出了依赖指定队列作为死信队列的所有队列。**  

```
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 参考 (V* 5) [ListDeadLetterSourceQueues](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SQSQueue`
<a name="sqs_ListQueues_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SQSQueue`。

**适用于 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 参考 (V* 5) [ListQueues](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SQSQueueAttribute`
<a name="sqs_GetQueueAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SQSQueueAttribute`。

**适用于 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 参考 (V* 5) [GetQueueAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SQSQueueUrl`
<a name="sqs_GetQueueUrl_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SQSQueueUrl`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出了具有指定名称的队列的 URL。**  

```
Get-SQSQueueUrl -QueueName MyQueue
```
**输出**：  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetQueueUrl](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-SQSQueue`
<a name="sqs_CreateQueue_powershell_topic"></a>

以下代码示例演示了如何使用 `New-SQSQueue`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用指定名称创建队列。**  

```
New-SQSQueue -QueueName MyQueue
```
**输出**：  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateQueue](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Receive-SQSMessage`
<a name="sqs_ReceiveMessage_powershell_topic"></a>

以下代码示例演示了如何使用 `Receive-SQSMessage`。

**适用于 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 参考 (V* 5) [ReceiveMessage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SQSMessage`
<a name="sqs_DeleteMessage_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SQSMessage`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了指定队列中具有指定接收句柄的消息。**  

```
Remove-SQSMessage -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -ReceiptHandle AQEBd329...v6gl8Q==
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteMessage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SQSMessageBatch`
<a name="sqs_DeleteMessageBatch_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SQSMessageBatch`。

**适用于 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 参考 (V* 5) [DeleteMessageBatch](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SQSPermission`
<a name="sqs_RemovePermission_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SQSPermission`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从指定队列中删除具有指定标签的权限设置。**  

```
Remove-SQSPermission -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RemovePermission](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SQSQueue`
<a name="sqs_DeleteQueue_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SQSQueue`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除了指定队列。**  

```
Remove-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteQueue](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Send-SQSMessage`
<a name="sqs_SendMessage_powershell_topic"></a>

以下代码示例演示了如何使用 `Send-SQSMessage`。

**适用于 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 参考 (V* 5) [SendMessage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Send-SQSMessageBatch`
<a name="sqs_SendMessageBatch_powershell_topic"></a>

以下代码示例演示了如何使用 `Send-SQSMessageBatch`。

**适用于 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 参考 (V* 5) [SendMessageBatch](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Set-SQSQueueAttribute`
<a name="sqs_SetQueueAttributes_powershell_topic"></a>

以下代码示例演示了如何使用 `Set-SQSQueueAttribute`。

**适用于 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 参考 (V* 5) [SetQueueAttributes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS STS 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_sts_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS STS的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Convert-STSAuthorizationMessage`
<a name="sts_DecodeAuthorizationMessage_powershell_topic"></a>

以下代码示例演示了如何使用 `Convert-STSAuthorizationMessage`。

**适用于 PowerShell V5 的工具**  
**示例 1：对为响应请求而返回的所提供编码消息内容中包含的其他信息进行解码。对其他信息进行编码的原因是，授权状态的详细信息可能构成请求操作的用户不应看到的特权信息。**  

```
Convert-STSAuthorizationMessage -EncodedMessage "...encoded message..."
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DecodeAuthorizationMessage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-STSFederationToken`
<a name="sts_GetFederationToken_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-STSFederationToken`。

**适用于 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 参考 (V* 5) [GetFederationToken](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-STSSessionToken`
<a name="sts_GetSessionToken_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-STSSessionToken`。

**适用于 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 参考 (V* 5) [GetSessionToken](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Use-STSRole`
<a name="sts_AssumeRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Use-STSRole`。

**适用于 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 参考 (V* 5) [AssumeRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Use-STSWebIdentityRole`
<a name="sts_AssumeRoleWithWebIdentity_powershell_topic"></a>

以下代码示例演示了如何使用 `Use-STSWebIdentityRole`。

**适用于 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 参考 (V* 5) [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 支持 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_support_code_examples"></a>

以下代码示例向您展示了如何使用带 支持的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-ASACommunicationToCase`
<a name="support_AddCommunicationToCase_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-ASACommunicationToCase`。

**适用于 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 参考 (V* 5) [AddCommunicationToCase](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASACase`
<a name="support_DescribeCases_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASACase`。

**适用于 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 参考 (V* 5) [DescribeCases](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASACommunication`
<a name="support_DescribeCommunications_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASACommunication`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定案例的所有通信。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
**示例 2：返回自协调世界时 2012 年 1 月 1 日午夜以来针对指定案例的所有通信。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -AfterTime "2012-01-10T00:00Z"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeCommunications](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASAService`
<a name="support_DescribeServices_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASAService`。

**适用于 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 参考 (V* 5) [DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASASeverityLevel`
<a name="support_DescribeSeverityLevels_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASASeverityLevel`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回可分配给 Support 案例的 AWS 严重性级别列表。**  

```
Get-ASASeverityLevel
```
**示例 2：返回可以分配给 Support 案例的 AWS 严重性级别列表。级别名称以日语返回。**  

```
Get-ASASeverityLevel -Language "ja"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeSeverityLevels](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASATrustedAdvisorCheck`
<a name="support_DescribeTrustedAdvisorChecks_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASATrustedAdvisorCheck`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 Trusted Advisor 检查的集合。必须指定 Language 参数，该参数可以接受“en”（表示英语输出），也可以接受“ja”（表示日语输出）。**  

```
Get-ASATrustedAdvisorCheck -Language "en"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTrustedAdvisorChecks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASATrustedAdvisorCheckRefreshStatus`
<a name="support_DescribeTrustedAdvisorCheckRefreshStatuses_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASATrustedAdvisorCheckRefreshStatus`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定检查的刷新请求的当前状态。Request-ASATrusted AdvisorCheckRefresh 可用于请求刷新支票的状态信息。**  

```
Get-ASATrustedAdvisorCheckRefreshStatus -CheckId @("checkid1", "checkid2")
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTrustedAdvisorCheckRefreshStatuses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASATrustedAdvisorCheckResult`
<a name="support_DescribeTrustedAdvisorCheckResult_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASATrustedAdvisorCheckResult`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回 Trusted Advisor 检查的结果。可用 Trusted Advisor 支票列表可以使用 Get-获取ASATrustedAdvisorChecks。输出是检查的总体状态、上次运行检查的时间戳以及特定检查的唯一 checkid。要以日语输出结果，请添加 -Language“ja”参数。**  

```
Get-ASATrustedAdvisorCheckResult -CheckId "checkid1"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTrustedAdvisorCheckResult](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-ASATrustedAdvisorCheckSummary`
<a name="support_DescribeTrustedAdvisorCheckSummaries_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-ASATrustedAdvisorCheckSummary`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定 Trusted Advisor 检查的最新摘要。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId "checkid1"
```
**示例 2：返回指定 Trusted Advisor 检查的最新摘要。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId @("checkid1", "checkid2")
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTrustedAdvisorCheckSummaries](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-ASACase`
<a name="support_CreateCase_powershell_topic"></a>

以下代码示例演示了如何使用 `New-ASACase`。

**适用于 PowerShell V5 的工具**  
**示例 1：在 Su AWS pport Center 中创建新案例。-ServiceCode 和-CategoryCode 参数的值可以使用 Get-ASAService cmdlet 获取。-SeverityCode 参数的值可以使用 Get-ASASeverityLevel cmdlet 获得。-IssueType 参数值可以是 “客户服务” 或 “技术”。如果成功，则 AWS 输出 Support 案例编号。默认情况下，案例将用英语处理，要使用日语，请添加 -Language“ja”参数。-ServiceCode、-CategoryCode、-主题和-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 参考 (V* 5) [CreateCase](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Request-ASATrustedAdvisorCheckRefresh`
<a name="support_RefreshTrustedAdvisorCheck_powershell_topic"></a>

以下代码示例演示了如何使用 `Request-ASATrustedAdvisorCheckRefresh`。

**适用于 PowerShell V5 的工具**  
**示例 1：请求刷新指定的 Trusted Advisor 检查。**  

```
Request-ASATrustedAdvisorCheckRefresh -CheckId "checkid1"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RefreshTrustedAdvisorCheck](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Resolve-ASACase`
<a name="support_ResolveCase_powershell_topic"></a>

以下代码示例演示了如何使用 `Resolve-ASACase`。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定案例的初始状态和完成用于解决该案例的调用后的当前状态。**  

```
Resolve-ASACase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResolveCase](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Systems Manager 示例
<a name="powershell_ssm_code_examples"></a>

以下代码示例向您展示了如何使用带有 Systems Manager 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Add-SSMResourceTag`
<a name="ssm_AddTagsToResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Add-SSMResourceTag`。

**适用于 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 参考 (V* 5) [AddTagsToResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-SSMDocumentPermission`
<a name="ssm_ModifyDocumentPermission_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-SSMDocumentPermission`。

**适用于 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 参考 (V* 5) [ModifyDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMActivation`
<a name="ssm_DescribeActivations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMActivation`。

**适用于 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 参考 (V* 5) [DescribeActivations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAssociation`
<a name="ssm_DescribeAssociation_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAssociation`。

**适用于 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 参考 (V* 5) [DescribeAssociation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAssociationExecution`
<a name="ssm_DescribeAssociationExecutions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAssociationExecution`。

**适用于 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 参考 (V* 5) [DescribeAssociationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAssociationExecutionTarget`
<a name="ssm_DescribeAssociationExecutionTargets_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAssociationExecutionTarget`。

**适用于 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 参考 (V* 5) [DescribeAssociationExecutionTargets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAssociationList`
<a name="ssm_ListAssociations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAssociationList`。

**适用于 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 参考 (V* 5) [ListAssociations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAssociationVersionList`
<a name="ssm_ListAssociationVersions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAssociationVersionList`。

**适用于 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 参考 (V* 5) [ListAssociationVersions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAutomationExecution`
<a name="ssm_GetAutomationExecution_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAutomationExecution`。

**适用于 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 参考 (V* 5) [GetAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAutomationExecutionList`
<a name="ssm_DescribeAutomationExecutions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAutomationExecutionList`。

**适用于 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 外的执行的 executionID、文档、执行 start/end 时间戳**  

```
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 参考 (V* 5) [DescribeAutomationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAutomationStepExecution`
<a name="ssm_DescribeAutomationStepExecutions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAutomationStepExecution`。

**适用于 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 参考 (V* 5) [DescribeAutomationStepExecutions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMAvailablePatch`
<a name="ssm_DescribeAvailablePatches_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMAvailablePatch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取 MSRC 严重性为“严重”的、适用于 Windows Server 2012 的所有可用补丁。此示例使用的语法需要 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 天内发布且适用于与 2019 年匹配 WindowsServer的商品的所有更新**  

```
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 参考 (V* 5) [DescribeAvailablePatches](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMCommand`
<a name="ssm_ListCommands_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMCommand`。

**适用于 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 参考 (V* 5) [ListCommands](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMCommandInvocation`
<a name="ssm_ListCommandInvocations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMCommandInvocation`。

**适用于 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- CommandPlugins 5123-45c1-234f5612345f 的调用**  

```
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 参考 (V* 5) [ListCommandInvocations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMCommandInvocationDetail`
<a name="ssm_GetCommandInvocation_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMCommandInvocationDetail`。

**适用于 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 参考 (V* 5) [GetCommandInvocation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMComplianceItemList`
<a name="ssm_ListComplianceItems_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMComplianceItemList`。

**适用于 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 参考 (V* 5) [ListComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMComplianceSummaryList`
<a name="ssm_ListComplianceSummaries_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMComplianceSummaryList`。

**适用于 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 参考 (V* 5) [ListComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMConnectionStatus`
<a name="ssm_GetConnectionStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMConnectionStatus`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例检索实例的 Session Manager 连接状态，以确定其是否已连接并准备好接收 Session Manager 连接。**  

```
Get-SSMConnectionStatus -Target i-0a1caf234f12d3dc4
```
**输出**：  

```
Status    Target
------    ------
Connected i-0a1caf234f12d3dc4
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMDefaultPatchBaseline`
<a name="ssm_GetDefaultPatchBaseline_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMDefaultPatchBaseline`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例显示默认补丁基准。**  

```
Get-SSMDefaultPatchBaseline
```
**输出**：  

```
arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMDeployablePatchSnapshotForInstance`
<a name="ssm_GetDeployablePatchSnapshotForInstance_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMDeployablePatchSnapshotForInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例显示实例使用的补丁基准的当前快照。此命令必须使用实例凭证从实例运行。为确保其使用实例证书，该示例将 `Amazon.Runtime.InstanceProfileAWSCredentials` 对象传递给 Credentials 参数。**  

```
$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 参考 (V* 5) [GetDeployablePatchSnapshotForInstance](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMDocument`
<a name="ssm_GetDocument_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMDocument`。

**适用于 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 参考 (V* 5) [GetDocument](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMDocumentDescription`
<a name="ssm_DescribeDocument_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMDocumentDescription`。

**适用于 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 参考 (V* 5) [DescribeDocument](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMDocumentList`
<a name="ssm_ListDocuments_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMDocumentList`。

**适用于 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 参考 (V* 5) [ListDocuments](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMDocumentPermission`
<a name="ssm_DescribeDocumentPermission_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMDocumentPermission`。

**适用于 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 参考 (V* 5) [DescribeDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMDocumentVersionList`
<a name="ssm_ListDocumentVersions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMDocumentVersionList`。

**适用于 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 参考 (V* 5) [ListDocumentVersions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMEffectiveInstanceAssociationList`
<a name="ssm_DescribeEffectiveInstanceAssociations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMEffectiveInstanceAssociationList`。

**适用于 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 参考 (V* 5) [DescribeEffectiveInstanceAssociations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMEffectivePatchesForPatchBaseline`
<a name="ssm_DescribeEffectivePatchesForPatchBaseline_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMEffectivePatchesForPatchBaseline`。

**适用于 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 参考 (V* 5) [DescribeEffectivePatchesForPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInstanceAssociationsStatus`
<a name="ssm_DescribeInstanceAssociationsStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInstanceAssociationsStatus`。

**适用于 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 参考 (V* 5) [DescribeInstanceAssociationsStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInstanceInformation`
<a name="ssm_DescribeInstanceInformation_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInstanceInformation`。

**适用于 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`的`2.2.800.0`那些 AWS 系统管理器实例。你可以在 InstanceInformation API 参考主题 (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1 InstanceInformation .html \$1systemsmanager-Type--InstanceInformation) 中找到有效的-Filter 键值列表。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 参数筛选结果，仅筛选区域中`us-east-1`带`Windows`或`PlatformTypes`的那些 AWS 系统管理器实例`Linux`。您可以在 InstanceInformationFilter API 参考主题 (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1 InstanceInformationFilter .html) 中找到有效的InstanceInformationFilterList 键值列表。**  

```
$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 参考 (V* 5) [DescribeInstanceInformation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInstancePatch`
<a name="ssm_DescribeInstancePatches_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInstancePatch`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取实例的补丁合规性详细信息。**  

```
Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeInstancePatches](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInstancePatchState`
<a name="ssm_DescribeInstancePatchStates_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInstancePatchState`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取实例的补丁摘要状态。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407"
```
**示例 2：此示例获取两个实例的补丁摘要状态。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407","i-09a618aec652973a9"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeInstancePatchStates](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInstancePatchStatesForPatchGroup`
<a name="ssm_DescribeInstancePatchStatesForPatchGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInstancePatchStatesForPatchGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取补丁组每个实例的补丁摘要状态。**  

```
Get-SSMInstancePatchStatesForPatchGroup -PatchGroup "Production"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeInstancePatchStatesForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInventory`
<a name="ssm_GetInventory_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInventory`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取清单的自定义元数据。**  

```
Get-SSMInventory
```
**输出**：  

```
Data                                                                                  Id
----                                                                                  --
{[AWS:InstanceInformation, Amazon.SimpleSystemsManagement.Model.InventoryResultItem]} i-0cb2b964d3e14fd9f
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetInventory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInventoryEntriesList`
<a name="ssm_ListInventoryEntries_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInventoryEntriesList`。

**适用于 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 参考 (V* 5) [ListInventoryEntries](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMInventoryEntryList`
<a name="ssm_Get-SSMInventoryEntryList_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInventoryEntryList`。

**适用于 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 的详细信息，请参阅 [Get-SSMInventory EntryList in AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/v5/reference) *Cmdlet 参考 (V5)*。

### `Get-SSMInventorySchema`
<a name="ssm_GetInventorySchema_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMInventorySchema`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例返回账户清单类型名称列表。**  

```
Get-SSMInventorySchema
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetInventorySchema](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMLatestEC2Image`
<a name="ssm_Get-SSMLatestEC2Image_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMLatestEC2Image`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出了所有最新的 Windows AMIs。**  

```
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：此示例列出了所有与指定通配符表达式 AMIs 匹配的最新窗口。**  

```
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 参考文档 (V* 5) 中的[获取SSMLatestEC2图片](https://docs.aws.amazon.com/powershell/v5/reference)。

### `Get-SSMMaintenanceWindow`
<a name="ssm_GetMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindow`。

**适用于 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 参考 (V* 5) [GetMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowExecution`
<a name="ssm_GetMaintenanceWindowExecution_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowExecution`。

**适用于 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 参考 (V* 5) [GetMaintenanceWindowExecution](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowExecutionList`
<a name="ssm_DescribeMaintenanceWindowExecutions_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowExecutionList`。

**适用于 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 参考 (V* 5) [DescribeMaintenanceWindowExecutions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowExecutionTask`
<a name="ssm_GetMaintenanceWindowExecutionTask_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowExecutionTask`。

**适用于 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 参考 (V* 5) [GetMaintenanceWindowExecutionTask](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowExecutionTaskInvocationList`
<a name="ssm_DescribeMaintenanceWindowExecutionTaskInvocations_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowExecutionTaskInvocationList`。

**适用于 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 参考 (V* 5) [DescribeMaintenanceWindowExecutionTaskInvocations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowExecutionTaskList`
<a name="ssm_DescribeMaintenanceWindowExecutionTasks_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowExecutionTaskList`。

**适用于 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 参考 (V* 5) [DescribeMaintenanceWindowExecutionTasks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowList`
<a name="ssm_DescribeMaintenanceWindows_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowList`。

**适用于 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 参考 (V* 5) [DescribeMaintenanceWindows](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowTarget`
<a name="ssm_DescribeMaintenanceWindowTargets_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowTarget`。

**适用于 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 参考 (V* 5) [DescribeMaintenanceWindowTargets](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMMaintenanceWindowTaskList`
<a name="ssm_DescribeMaintenanceWindowTasks_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMMaintenanceWindowTaskList`。

**适用于 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 参考 (V* 5) [DescribeMaintenanceWindowTasks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMParameterHistory`
<a name="ssm_GetParameterHistory_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMParameterHistory`。

**适用于 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 参考 (V* 5) [GetParameterHistory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMParameterList`
<a name="ssm_DescribeParameters_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMParameterList`。

**适用于 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 参考 (V* 5) [DescribeParameters](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMParameterValue`
<a name="ssm_GetParameters_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMParameterValue`。

**适用于 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 参考 (V* 5) [GetParameters](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMPatchBaseline`
<a name="ssm_DescribePatchBaselines_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMPatchBaseline`。

**适用于 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 参考 (V* 5) [DescribePatchBaselines](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMPatchBaselineDetail`
<a name="ssm_GetPatchBaseline_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMPatchBaselineDetail`。

**适用于 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 参考 (V* 5) [GetPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMPatchBaselineForPatchGroup`
<a name="ssm_GetPatchBaselineForPatchGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMPatchBaselineForPatchGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例显示补丁组的补丁基准。**  

```
Get-SSMPatchBaselineForPatchGroup -PatchGroup "Production"
```
**输出**：  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMPatchGroup`
<a name="ssm_DescribePatchGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMPatchGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出补丁组注册。**  

```
Get-SSMPatchGroup
```
**输出**：  

```
BaselineIdentity                                           PatchGroup
----------------                                           ----------
Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribePatchGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMPatchGroupState`
<a name="ssm_DescribePatchGroupState_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMPatchGroupState`。

**适用于 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 参考 (V* 5) [DescribePatchGroupState](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMResourceComplianceSummaryList`
<a name="ssm_ListResourceComplianceSummaries_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMResourceComplianceSummaryList`。

**适用于 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 参考 (V* 5) [ListResourceComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-SSMResourceTag`
<a name="ssm_ListTagsForResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-SSMResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出维护时段的标签。**  

```
Get-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow"
```
**输出**：  

```
Key   Value
---   -----
Stack Production
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-SSMActivation`
<a name="ssm_CreateActivation_powershell_topic"></a>

以下代码示例演示了如何使用 `New-SSMActivation`。

**适用于 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 参考 (V* 5) [CreateActivation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-SSMAssociation`
<a name="ssm_CreateAssociation_powershell_topic"></a>

以下代码示例演示了如何使用 `New-SSMAssociation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用实例将配置文档与实例关联起来 IDs。**  

```
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 参考 (V* 5) [CreateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-SSMAssociationFromBatch`
<a name="ssm_CreateAssociationBatch_powershell_topic"></a>

以下代码示例演示了如何使用 `New-SSMAssociationFromBatch`。

**适用于 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 参考 (V* 5) [CreateAssociationBatch](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-SSMDocument`
<a name="ssm_CreateDocument_powershell_topic"></a>

以下代码示例演示了如何使用 `New-SSMDocument`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在您的账户中创建一个文档。该文档必须采用 JSON 格式。有关编写配置文档的更多信息，请参阅《SSM API Reference》中的配置文档。**  

```
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 参考 (V* 5) [CreateDocument](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-SSMMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `New-SSMMaintenanceWindow`。

**适用于 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 参考 (V* 5) [CreateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-SSMPatchBaseline`
<a name="ssm_CreatePatchBaseline_powershell_topic"></a>

以下代码示例演示了如何使用 `New-SSMPatchBaseline`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建补丁基准，用于在 Microsoft 发布补丁 7 天后为在生产环境中运行 Windows Server 2019 的托管式实例批准补丁。**  

```
$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 参考 (V* 5) [CreatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-SSMDefaultPatchBaseline`
<a name="ssm_RegisterDefaultPatchBaseline_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-SSMDefaultPatchBaseline`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将补丁基准注册为默认补丁基准。**  

```
Register-SSMDefaultPatchBaseline -BaselineId "pb-03da896ca3b68b639"
```
**输出**：  

```
pb-03da896ca3b68b639
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RegisterDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-SSMPatchBaselineForPatchGroup`
<a name="ssm_RegisterPatchBaselineForPatchGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-SSMPatchBaselineForPatchGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为补丁组注册补丁基准。**  

```
Register-SSMPatchBaselineForPatchGroup -BaselineId "pb-03da896ca3b68b639" -PatchGroup "Production"
```
**输出**：  

```
BaselineId           PatchGroup
----------           ----------
pb-03da896ca3b68b639 Production
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RegisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-SSMTargetWithMaintenanceWindow`
<a name="ssm_RegisterTargetWithMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-SSMTargetWithMaintenanceWindow`。

**适用于 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 参考 (V* 5) [RegisterTargetWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-SSMTaskWithMaintenanceWindow`
<a name="ssm_RegisterTaskWithMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-SSMTaskWithMaintenanceWindow`。

**适用于 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：此示例为运行命令文档 `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 自动化任务`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 参考 (V* 5) [RegisterTaskWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SSMActivation`
<a name="ssm_DeleteActivation_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SSMActivation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除激活。如果此命令成功，则无任何输出。**  

```
Remove-SSMActivation -ActivationId "08e51e79-1e36-446c-8e63-9458569c1363"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteActivation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SSMAssociation`
<a name="ssm_DeleteAssociation_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SSMAssociation`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除实例和文档之间的关联。如果此命令成功，则无任何输出。**  

```
Remove-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteAssociation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SSMDocument`
<a name="ssm_DeleteDocument_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SSMDocument`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除文档。如果此命令成功，则无任何输出。**  

```
Remove-SSMDocument -Name "RunShellScript"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteDocument](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SSMMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SSMMaintenanceWindow`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除维护时段。**  

```
Remove-SSMMaintenanceWindow -WindowId "mw-06d59c1a07c022145"
```
**输出**：  

```
mw-06d59c1a07c022145
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SSMParameter`
<a name="ssm_DeleteParameter_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SSMParameter`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除一个参数。如果此命令成功，则无任何输出。**  

```
Remove-SSMParameter -Name "helloWorld"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteParameter](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SSMPatchBaseline`
<a name="ssm_DeletePatchBaseline_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SSMPatchBaseline`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除补丁基准。**  

```
Remove-SSMPatchBaseline -BaselineId "pb-045f10b4f382baeda"
```
**输出**：  

```
pb-045f10b4f382baeda
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeletePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-SSMResourceTag`
<a name="ssm_RemoveTagsFromResource_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-SSMResourceTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从维护时段中删除标签。如果此命令成功，则无任何输出。**  

```
Remove-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -TagKey "Production"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Send-SSMCommand`
<a name="ssm_SendCommand_powershell_topic"></a>

以下代码示例演示了如何使用 `Send-SSMCommand`。

**适用于 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 参考 (V* 5) [SendCommand](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-SSMAutomationExecution`
<a name="ssm_StartAutomationExecution_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-SSMAutomationExecution`。

**适用于 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 参考 (V* 5) [StartAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Start-SSMSession`
<a name="ssm_StartSession_powershell_topic"></a>

以下代码示例演示了如何使用 `Start-SSMSession`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为会话管理器会话启动与目标的连接，从而启用端口转发。注意：如果尚未使用进行设置，则需要添加区域参数 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：此示例为会话管理器会话创建与指定实例的交互式会话。**  

```
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 参考 (V* 5) [StartSession](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-SSMAutomationExecution`
<a name="ssm_StopAutomationExecution_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-SSMAutomationExecution`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例停止自动化执行。如果此命令成功，则无任何输出。**  

```
Stop-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StopAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-SSMCommand`
<a name="ssm_CancelCommand_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-SSMCommand`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例尝试取消命令。如果操作成功，则无任何输出。**  

```
Stop-SSMCommand -CommandId "9ded293e-e792-4440-8e3e-7b8ec5feaa38"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CancelCommand](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-SSMManagedInstance`
<a name="ssm_DeregisterManagedInstance_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-SSMManagedInstance`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例取消注册托管式实例。如果此命令成功，则无任何输出。**  

```
Unregister-SSMManagedInstance -InstanceId "mi-08ab247cdf1046573"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeregisterManagedInstance](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-SSMPatchBaselineForPatchGroup`
<a name="ssm_DeregisterPatchBaselineForPatchGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-SSMPatchBaselineForPatchGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从补丁基准中取消注册补丁组。**  

```
Unregister-SSMPatchBaselineForPatchGroup -BaselineId "pb-045f10b4f382baeda" -PatchGroup "Production"
```
**输出**：  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeregisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-SSMTargetFromMaintenanceWindow`
<a name="ssm_DeregisterTargetFromMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-SSMTargetFromMaintenanceWindow`。

**适用于 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 参考 (V* 5) [DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-SSMTaskFromMaintenanceWindow`
<a name="ssm_DeregisterTaskFromMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-SSMTaskFromMaintenanceWindow`。

**适用于 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 参考 (V* 5) [DeregisterTaskFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-SSMAssociation`
<a name="ssm_UpdateAssociation_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-SSMAssociation`。

**适用于 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 参考 (V* 5) [UpdateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-SSMAssociationStatus`
<a name="ssm_UpdateAssociationStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-SSMAssociationStatus`。

**适用于 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 参考 (V* 5) [UpdateAssociationStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-SSMDocument`
<a name="ssm_UpdateDocument_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-SSMDocument`。

**适用于 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 参考 (V* 5) [UpdateDocument](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-SSMDocumentDefaultVersion`
<a name="ssm_UpdateDocumentDefaultVersion_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-SSMDocumentDefaultVersion`。

**适用于 PowerShell V5 的工具**  
**示例 1：此实例更新文档的默认版本。您可以通过 “Get-SSMDocumentVersionList” cmdlet 获取可用的文档版本。**  

```
Update-SSMDocumentDefaultVersion -Name "RunShellScript" -DocumentVersion "2"
```
**输出**：  

```
DefaultVersion Name
-------------- ----
2              RunShellScript
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateDocumentDefaultVersion](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-SSMMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-SSMMaintenanceWindow`。

**适用于 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 参考 (V* 5) [UpdateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-SSMManagedInstanceRole`
<a name="ssm_UpdateManagedInstanceRole_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-SSMManagedInstanceRole`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新托管式实例的角色。如果此命令成功，则无任何输出。**  

```
Update-SSMManagedInstanceRole -InstanceId "mi-08ab247cdf1046573" -IamRole "AutomationRole"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateManagedInstanceRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Update-SSMPatchBaseline`
<a name="ssm_UpdatePatchBaseline_powershell_topic"></a>

以下代码示例演示了如何使用 `Update-SSMPatchBaseline`。

**适用于 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 参考 (V* 5) [UpdatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-SSMComplianceItem`
<a name="ssm_PutComplianceItems_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-SSMComplianceItem`。

**适用于 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 参考 (V* 5) [PutComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-SSMInventory`
<a name="ssm_PutInventory_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-SSMInventory`。

**适用于 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 参考 (V* 5) [PutInventory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Write-SSMParameter`
<a name="ssm_PutParameter_powershell_topic"></a>

以下代码示例演示了如何使用 `Write-SSMParameter`。

**适用于 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 参考 (V* 5) [PutParameter](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# 使用适用于 PowerShell V5 的工具的 Amazon Translate 示例
<a name="powershell_translate_code_examples"></a>

以下代码示例向您展示了如何使用带有 Amazon Translate 的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `ConvertTo-TRNTargetLanguage`
<a name="translate_TranslateText_powershell_topic"></a>

以下代码示例演示了如何使用 `ConvertTo-TRNTargetLanguage`。

**适用于 PowerShell V5 的工具**  
**示例 1：将指定的英文文本转换为法语。要转换的文本也可以作为 -Text 参数传递。**  

```
"Hello World" | ConvertTo-TRNTargetLanguage -SourceLanguageCode en -TargetLanguageCode fr
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [TranslateText](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# AWS WAFV2 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_wafv2_code_examples"></a>

以下代码示例向您展示了如何使用带 AWS WAFV2的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `New-WAF2WebACL`
<a name="wafv2_CreateWebAcl_powershell_topic"></a>

以下代码示例演示了如何使用 `New-WAF2WebACL`。

**适用于 PowerShell V5 的工具**  
**示例 1：此命令创建一个名为“waf-test”的新 Web ACL。请注意，根据服务 API 文档，“DefaultAction” 是必填属性。因此，应指定'-\$1All DefaultAction ow'''-DefaultAction \$1 and/or Block'的值。由于'-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 参考 (V* 5) [CreateWebAcl](https://docs.aws.amazon.com/powershell/v5/reference)中的。

# WorkSpaces 使用适用于 PowerShell V5 的工具的示例
<a name="powershell_workspaces_code_examples"></a>

以下代码示例向您展示了如何使用带 WorkSpaces的 AWS Tools for PowerShell V5 来执行操作和实现常见场景。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接，您可以从中找到有关如何在上下文中设置和运行代码的说明。

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

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

### `Approve-WKSIpRule`
<a name="workspaces_AuthorizeIpRules_powershell_topic"></a>

以下代码示例演示了如何使用 `Approve-WKSIpRule`。

**适用于 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 参考 (V* 5) [AuthorizeIpRules](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Copy-WKSWorkspaceImage`
<a name="workspaces_CopyWorkspaceImage_powershell_topic"></a>

以下代码示例演示了如何使用 `Copy-WKSWorkspaceImage`。

**适用于 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 参考 (V* 5) [CopyWorkspaceImage](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-WKSClientProperty`
<a name="workspaces_ModifyClientProperties_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-WKSClientProperty`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例为 Workspaces 客户端启用重新连接**  

```
Edit-WKSClientProperty -Region us-west-2 -ClientProperties_ReconnectEnabled "ENABLED" -ResourceId d-123414a369
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyClientProperties](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-WKSSelfServicePermission`
<a name="workspaces_ModifySelfservicePermissions_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-WKSSelfServicePermission`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用自助服务权限，以便为指定的目录更改计算类型并增加卷大小**  

```
Edit-WKSSelfservicePermission -Region us-west-2 -ResourceId d-123454a369 -SelfservicePermissions_ChangeComputeType ENABLED -SelfservicePermissions_IncreaseVolumeSize ENABLED
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifySelfservicePermissions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-WKSWorkspaceAccessProperty`
<a name="workspaces_ModifyWorkspaceAccessProperties_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-WKSWorkspaceAccessProperty`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例在 Android 和 Chrome 操作系统上针对指定目录启用工作空间访问**  

```
Edit-WKSWorkspaceAccessProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceAccessProperties_DeviceTypeAndroid ALLOW -WorkspaceAccessProperties_DeviceTypeChromeOs ALLOW
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyWorkspaceAccessProperties](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-WKSWorkspaceCreationProperty`
<a name="workspaces_ModifyWorkspaceCreationProperties_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-WKSWorkspaceCreationProperty`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例支持在创建工作空间时将互联网访问和维护模式设置为 true 作为默认值**  

```
Edit-WKSWorkspaceCreationProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceCreationProperties_EnableInternetAccess $true -WorkspaceCreationProperties_EnableMaintenanceMode $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyWorkspaceCreationProperties](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-WKSWorkspaceProperty`
<a name="workspaces_ModifyWorkspaceProperties_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-WKSWorkspaceProperty`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定工作空间的“工作空间运行模式”属性更改为“自动停止”**  

```
Edit-WKSWorkspaceProperty -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceProperties_RunningMode AUTO_STOP
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyWorkspaceProperties](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Edit-WKSWorkspaceState`
<a name="workspaces_ModifyWorkspaceState_powershell_topic"></a>

以下代码示例演示了如何使用 `Edit-WKSWorkspaceState`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定工作空间的状态更改为“可用”**  

```
Edit-WKSWorkspaceState -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceState AVAILABLE
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ModifyWorkspaceState](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSClientProperty`
<a name="workspaces_DescribeClientProperties_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSClientProperty`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定目录的工作空间客户端的客户端属性**  

```
Get-WKSClientProperty -ResourceId d-223562a123
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeClientProperties](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSIpGroup`
<a name="workspaces_DescribeIpGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSIpGroup`。

**适用于 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 参考 (V* 5) [DescribeIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSTag`
<a name="workspaces_DescribeTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取给定工作空间的标签**  

```
Get-WKSTag -WorkspaceId ws-w361s234r -Region us-west-2
```
**输出**：  

```
Key         Value
---         -----
auto-delete no
purpose     Workbench
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSWorkspace`
<a name="workspaces_DescribeWorkspaces_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSWorkspace`。

**适用于 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 \$1 WorkspaceProperties .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 参考 (V* 5) [DescribeWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSWorkspaceBundle`
<a name="workspaces_DescribeWorkspaceBundles_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSWorkspaceBundle`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取当前区域中所有工作空间捆绑包的详细信息**  

```
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 参考 (V* 5) [DescribeWorkspaceBundles](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSWorkspaceDirectory`
<a name="workspaces_DescribeWorkspaceDirectories_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSWorkspaceDirectory`。

**适用于 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 参考 (V* 5) [DescribeWorkspaceDirectories](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSWorkspaceImage`
<a name="workspaces_DescribeWorkspaceImages_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSWorkspaceImage`。

**适用于 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 参考 (V* 5) [DescribeWorkspaceImages](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSWorkspaceSnapshot`
<a name="workspaces_DescribeWorkspaceSnapshots_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSWorkspaceSnapshot`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例演示为指定工作空间创建的最新快照的时间戳**  

```
Get-WKSWorkspaceSnapshot -WorkspaceId ws-w361s100v
```
**输出**：  

```
RebuildSnapshots                   RestoreSnapshots
----------------                   ----------------
{Amazon.WorkSpaces.Model.Snapshot} {Amazon.WorkSpaces.Model.Snapshot}
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeWorkspaceSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Get-WKSWorkspacesConnectionStatus`
<a name="workspaces_DescribeWorkspacesConnectionStatus_powershell_topic"></a>

以下代码示例演示了如何使用 `Get-WKSWorkspacesConnectionStatus`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例获取指定工作空间的连接状态**  

```
Get-WKSWorkspacesConnectionStatus -WorkspaceId ws-w123s234r
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeWorkspacesConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-WKSIpGroup`
<a name="workspaces_CreateIpGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `New-WKSIpGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建了一个名为的空 IP 组 FreshEmptyIpGroup**  

```
New-WKSIpGroup -GroupName "FreshNewIPGroup"
```
**输出**：  

```
wsipg-w45rty4ty
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateIpGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-WKSTag`
<a name="workspaces_CreateTags_powershell_topic"></a>

以下代码示例演示了如何使用 `New-WKSTag`。

**适用于 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 参考 (V* 5) [CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `New-WKSWorkspace`
<a name="workspaces_CreateWorkspaces_powershell_topic"></a>

以下代码示例演示了如何使用 `New-WKSWorkspace`。

**适用于 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 参考 (V* 5) [CreateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-WKSIpGroup`
<a name="workspaces_AssociateIpGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-WKSIpGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的 IP 组注册到指定的目录**  

```
Register-WKSIpGroup -GroupId wsipg-23ahsdres -DirectoryId d-123412e123
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AssociateIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Register-WKSWorkspaceDirectory`
<a name="workspaces_RegisterWorkspaceDirectory_powershell_topic"></a>

以下代码示例演示了如何使用 `Register-WKSWorkspaceDirectory`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例注册 Workspaces 服务的指定目录**  

```
Register-WKSWorkspaceDirectory -DirectoryId d-123412a123 -EnableWorkDoc $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RegisterWorkspaceDirectory](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-WKSIpGroup`
<a name="workspaces_DeleteIpGroup_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-WKSIpGroup`。

**适用于 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 参考 (V* 5) [DeleteIpGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-WKSTag`
<a name="workspaces_DeleteTags_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-WKSTag`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例移除与工作空间关联的标签**  

```
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 参考 (V* 5) [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Remove-WKSWorkspace`
<a name="workspaces_TerminateWorkspaces_powershell_topic"></a>

以下代码示例演示了如何使用 `Remove-WKSWorkspace`。

**适用于 PowerShell V5 的工具**  
**示例 1：终止多个 WorkSpaces。使用-Force 开关会阻止 cmdlet 提示确认。**  

```
Remove-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0" -Force
```
**示例 2：检索所有你的集合， WorkSpaces 然后通过管道传递 IDs 到 Remove-的-WorkSpaceId 参数WKSWorkspace，终止所有的。 WorkSpacescmdlet 将在每个 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 参考 (V* 5) [TerminateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Reset-WKSWorkspace`
<a name="workspaces_RebuildWorkspaces_powershell_topic"></a>

以下代码示例演示了如何使用 `Reset-WKSWorkspace`。

**适用于 PowerShell V5 的工具**  
**示例 1：重建指定 WorkSpace的。**  

```
Reset-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**示例 2：检索所有你的集合， WorkSpaces 然后通过管道 IDs 将它们传递给 Reset-的-WorkSpaceId 参数WKSWorkspace，从而重新构建。 WorkSpaces **  

```
Get-WKSWorkspaces | Reset-WKSWorkspace
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RebuildWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Restart-WKSWorkspace`
<a name="workspaces_RebootWorkspaces_powershell_topic"></a>

以下代码示例演示了如何使用 `Restart-WKSWorkspace`。

**适用于 PowerShell V5 的工具**  
**示例 1：重新启动指定 WorkSpace的。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**示例 2：多次 WorkSpaces重启。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d","ws-5a6b7c8d"
```
**示例 3：检索所有你的集合， WorkSpaces 并将通过管道传递 IDs 给 Restart-的-WorkSpaceId 参数WKSWorkspace，从而 WorkSpaces 使重新启动。**  

```
Get-WKSWorkspaces | Restart-WKSWorkspace
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RebootWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Stop-WKSWorkspace`
<a name="workspaces_StopWorkspaces_powershell_topic"></a>

以下代码示例演示了如何使用 `Stop-WKSWorkspace`。

**适用于 PowerShell V5 的工具**  
**示例 1：停止多个 WorkSpaces。**  

```
Stop-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0"
```
**示例 2：检索所有你的集合， WorkSpaces 然后通过管道传递 IDs 给 Stop-的-WorkSpaceId 参数，WKSWorkspace WorkSpaces 从而导致停止。**  

```
Get-WKSWorkspaces | Stop-WKSWorkspace
```
**示例 3：此示例说明如何传递定义 WorkSpaces 要停止的 StopRequest 对象。**  

```
$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 参考 (V* 5) [StopWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)中的。

### `Unregister-WKSIpGroup`
<a name="workspaces_DisassociateIpGroups_powershell_topic"></a>

以下代码示例演示了如何使用 `Unregister-WKSIpGroup`。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从指定的目录中取消注册指定的 IP 组**  

```
Unregister-WKSIpGroup -GroupId wsipg-12abcdphq -DirectoryId d-123454b123
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisassociateIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。