

AWS Tools for PowerShell V4 已进入维护模式。

我们建议您迁移到 [AWS Tools for PowerShell V5](https://docs.aws.amazon.com/powershell/v5/userguide/)。有关如何迁移的更多详细信息和信息，请参阅我们的[维护模式公告](https://aws.amazon.com/blogs/developer/aws-tools-for-powershell-v4-maintenance-mode-announcement/)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

您可以使用 AWS Tools for PowerShell 执行与 Amazon EC2 相关的常见任务。

此处显示的示例命令假设您已为 PowerShell 会话设置了默认凭证和默认区域。因此，我们在调用 cmdlet 时不包括凭证或区域。有关更多信息，请参阅 [开始使用 AWS Tools for Windows PowerShell](pstools-getting-started.md)。

**Topics**
+ [创建密钥对](pstools-ec2-keypairs.md)
+ [创建安全组](pstools-ec2-sg.md)
+ [查找 AMI](pstools-ec2-get-amis.md)
+ [启动实例](pstools-ec2-launch.md)

# 创建密钥对
<a name="pstools-ec2-keypairs"></a>

以下 `New-EC2KeyPair` 示例创建密钥对并将其存储在 PowerShell 变量 `$myPSKeyPair` 中。

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

将密钥对对象通过管道传输到 `Get-Member` cmdlet 中以查看对象的结构。

```
PS > $myPSKeyPair | Get-Member

     TypeName: Amazon.EC2.Model.KeyPair

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

将密钥对对象通过管道传输到 `Format-List` cmdlet 以查看 `KeyName`、`KeyFingerprint` 和 `KeyMaterial` 成员的值。（为了便于阅读，输入内容已截断。）

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

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

`KeyMaterial` 成员存储密钥对的私有密钥。公有密钥存储在AWS中。您无法从AWS检索公有密钥，但是，您可以通过将私有密钥的 `KeyFingerprint` 与AWS返回的公有密钥的该值进行对比来验证公有密钥。

## 查看密钥对的指纹
<a name="get-ec2keypair"></a>

您可以使用 `Get-EC2KeyPair` cmdlet 查看密钥对的指纹。

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

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

## 存储私有密钥
<a name="store-ec2keypair"></a>

要将私有密钥存储到文件中，请将 `KeyFingerMaterial` 成员通过管道传输到 `Out-File` cmdlet。

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

在将私有密钥写入到文件中时，必须指定 `-Encoding ascii`。否则，`openssl` 等工具可能无法正确读取此文件。您可以使用类似于以下的命令来验证生成文件的格式是否正确：

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

（`openssl` 工具未包含在 AWS Tools for PowerShell 或 适用于 .NET 的 AWS SDK 中。）

## 删除密钥对
<a name="remove-ec2keypair"></a>

您需要密钥对来启动和连接到实例。在用完密钥对后，您可以将其删除。要从AWS中删除公有密钥，请使用 `Remove-EC2KeyPair` cmdlet。在出现提示时，按 `Enter` 可删除密钥对。

```
PS > Remove-EC2KeyPair -KeyName myPSKeyPair

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

变量 `$myPSKeyPair` 仍存在于当前 PowerShell 会话中，并仍包含密钥对信息。`myPSKeyPair.pem` 文件也存在。但是，公有密钥不再有效，因为密钥对的私有密钥不再存储在AWS中。

# 使用 Windows PowerShell 创建安全组
<a name="pstools-ec2-sg"></a>

您可以使用AWS Tools for PowerShell来创建和配置安全组。该操作以安全组 ID 作为响应。

如果您需要连接到您的实例，就必须配置安全组以允许 SSH 流量 (Linux) 或 RDP 流量 (Windows)。

**Topics**
+ [先决条件](#sg-prerequisites)
+ [为 EC2-VPC 创建安全组](#new-ec2securitygroup-vpc)

## 先决条件
<a name="sg-prerequisites"></a>

您需要您的计算机的公有 IP 地址，该地址使用 CIDR 表示法。您可以通过一项服务来获取本地计算机的公有 IP 地址。例如，Amazon 提供以下服务：[http://checkip.amazonaws.com/](http://checkip.amazonaws.com/) 或 [https://checkip.amazonaws.com/](https://checkip.amazonaws.com/)。要查找另一项可提供您的 IP 地址的服务，请使用搜索短语“what is my IP address”。如果您正通过 ISP 或从防火墙后面连接，没有静态 IP 地址，您需要找出客户端计算机可以使用的 IP 地址范围。

**警告**  
如果您指定 `0.0.0.0/0`，则会启用来自世界上任何 IP 地址的流量。对于 SSH 和 RDP 协议，您可能考虑这在测试环境下短时间内是可以接受的，但它对于生产环境并不安全。对于生产环境，请确保仅授权从适当的单个 IP 地址或地址范围进行访问。

## 为 EC2-VPC 创建安全组
<a name="new-ec2securitygroup-vpc"></a>

**警告**  
EC2-Classic 已于 2022 年 8 月 15 日停用。我们建议您从 EC2-Classic 迁移到 VPC。有关更多信息，请参阅博客文章 [EC2-Classic Networking is Retiring - Here's How to Prepare](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/)。

以下 `New-EC2SecurityGroup` 示例将添加 `-VpcId` 参数为指定的 VPC 创建安全组。

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

要查看安全组的初始配置，请使用 `Get-EC2SecurityGroup` cmdlet。默认情况下，VPC 的安全组中包含允许所有出站流量的规则。请注意，您不能通过名称引用 EC2-VPC 的安全组。

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

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

要为 TCP 端口 22 (SSH) 和 TCP 端口 3389 上的入站流量定义权限，请使用 `New-Object` cmdlet。以下示例脚本为从来自单个 IP 地址 `203.0.113.25/32` 的 TCP 端口 22 和 3389 定义权限。

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

要验证已更新安全组，请再次使用 `Get-EC2SecurityGroup` cmdlet。

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

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

要查看入站规则，您可以从上一个命令返回的集合对象中检索 `IpPermissions` 属性。

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

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

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

# 使用 Windows 查找亚马逊计算机映像 PowerShell
<a name="pstools-ec2-get-amis"></a>

在启动 Amazon EC2 实例时，您需要指定一个 Amazon Machine Image (AMI) 以用作该实例的模板。但是， IDs AWS Windows 版经常 AMIs 更改，因为 AWS AMIs 提供了最新的更新和安全增强功能。你可以使用[Get-EC2Image](https://docs.aws.amazon.com/powershell/v4/reference/items/Get-EC2Image.html)和 [Get-EC2ImageByName](https://docs.aws.amazon.com/powershell/v4/reference/items/Get-EC2ImageByName.html)cmdlet 来查找当前 Windows AMIs 并获取它们。 IDs

**Topics**
+ [Get-EC2Image](#pstools-ec2-get-image)
+ [Get-EC2ImageByName](#pstools-ec2-get-ec2imagebyname)

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

`Get-EC2Image`cmdlet 会检索您可以 AMIs 使用的列表。

将`-Owner`参数与数组值一起使用，`amazon, self` AMIs 以便仅`Get-EC2Image`检索属于 Amazon 或您的数组。在此上下文中，*您*指的是您要使用其凭证来调用 cmdlet 的用户。

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

可使用 `-Filter` 参数限定结果的范围。要指定筛选条件，可创建类型为 `Amazon.EC2.Model.Filter` 的对象。例如，使用以下筛选器仅显示 Windows AMIs。

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

以下是 cmdlet AMIs 返回的命令的示例；上一个命令的实际输出为许多命令提供了信息。 AMIs

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

## Get-EC2ImageByName
<a name="pstools-ec2-get-ec2imagebyname"></a>

`Get-EC2ImageByName`cmdlet 允许您 AMIs 根据感兴趣的服务器配置类型筛选 AWS Windows 列表。

在没有参数的情况下运行时（如下所示），cmdlet 会发出整组当前筛选条件名称：

```
PS > Get-EC2ImageByName

WINDOWS_2016_BASE
WINDOWS_2016_NANO
WINDOWS_2016_CORE
WINDOWS_2016_CONTAINER
WINDOWS_2016_SQL_SERVER_ENTERPRISE_2016
WINDOWS_2016_SQL_SERVER_STANDARD_2016
WINDOWS_2016_SQL_SERVER_WEB_2016
WINDOWS_2016_SQL_SERVER_EXPRESS_2016
WINDOWS_2012R2_BASE
WINDOWS_2012R2_CORE
WINDOWS_2012R2_SQL_SERVER_EXPRESS_2016
WINDOWS_2012R2_SQL_SERVER_STANDARD_2016
WINDOWS_2012R2_SQL_SERVER_WEB_2016
WINDOWS_2012R2_SQL_SERVER_EXPRESS_2014
WINDOWS_2012R2_SQL_SERVER_STANDARD_2014
WINDOWS_2012R2_SQL_SERVER_WEB_2014
WINDOWS_2012_BASE
WINDOWS_2012_SQL_SERVER_EXPRESS_2014
WINDOWS_2012_SQL_SERVER_STANDARD_2014
WINDOWS_2012_SQL_SERVER_WEB_2014
WINDOWS_2012_SQL_SERVER_EXPRESS_2012
WINDOWS_2012_SQL_SERVER_STANDARD_2012
WINDOWS_2012_SQL_SERVER_WEB_2012
WINDOWS_2012_SQL_SERVER_EXPRESS_2008
WINDOWS_2012_SQL_SERVER_STANDARD_2008
WINDOWS_2012_SQL_SERVER_WEB_2008
WINDOWS_2008R2_BASE
WINDOWS_2008R2_SQL_SERVER_EXPRESS_2012
WINDOWS_2008R2_SQL_SERVER_STANDARD_2012
WINDOWS_2008R2_SQL_SERVER_WEB_2012
WINDOWS_2008R2_SQL_SERVER_EXPRESS_2008
WINDOWS_2008R2_SQL_SERVER_STANDARD_2008
WINDOWS_2008R2_SQL_SERVER_WEB_2008
WINDOWS_2008RTM_BASE
WINDOWS_2008RTM_SQL_SERVER_EXPRESS_2008
WINDOWS_2008RTM_SQL_SERVER_STANDARD_2008
WINDOWS_2008_BEANSTALK_IIS75
WINDOWS_2012_BEANSTALK_IIS8
VPC_NAT
```

要缩小返回的映像集，请使用 `Names` 参数指定一个或多个筛选条件名称。

```
PS > Get-EC2ImageByName -Names WINDOWS_2016_CORE

Architecture        : x86_64
BlockDeviceMappings : {/dev/sda1, xvdca, xvdcb, xvdcc…}
CreationDate        : 2019-08-16T09:36:09.000Z
Description         : Microsoft Windows Server 2016 Core Locale English AMI provided by Amazon
EnaSupport          : True
Hypervisor          : xen
ImageId             : ami-06f2a2afca06f15fc
ImageLocation       : amazon/Windows_Server-2016-English-Core-Base-2019.08.16
ImageOwnerAlias     : amazon
ImageType           : machine
KernelId            : 
Name                : Windows_Server-2016-English-Core-Base-2019.08.16
OwnerId             : 801119661308
Platform            : Windows
ProductCodes        : {}
Public              : True
RamdiskId           : 
RootDeviceName      : /dev/sda1
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         : 
Tags                : {}
VirtualizationType  : hvm
```

# 使用 Windows PowerShell 启动 Amazon EC2 实例
<a name="pstools-ec2-launch"></a>

要启动 Amazon EC2 实例，您需要您在之前的章节中创建的密钥对和安全组。您还需要 Amazon Machine Image (AMI) 的 ID。有关更多信息，请参阅以下文档：
+  [创建密钥对](pstools-ec2-keypairs.md) 
+  [使用 Windows PowerShell 创建安全组](pstools-ec2-sg.md) 
+  [使用 Windows PowerShell 查找 Amazon Machine Image](pstools-ec2-get-amis.md) 

**重要**  
如果您启动不在免费套餐范围内的实例，那么在启动实例后您将需要付费，费用按实例的运行时间计算，即使实例处于闲置状态也需付费。

**Topics**
+ [在 VPC 中启动实例](#new-ec2instance-vpc)
+ [在 VPC 中启动 Spot 实例](#new-ec2instance-spot)

## 在 VPC 中启动实例
<a name="new-ec2instance-vpc"></a>

**警告**  
EC2-Classic 已于 2022 年 8 月 15 日停用。我们建议您从 EC2-Classic 迁移到 VPC。有关更多信息，请参阅博客文章 [EC2-Classic Networking is Retiring - Here's How to Prepare](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/)。

以下命令在指定的私有子网中创建一个 `m1.small` 实例。安全组必须对指定的子网有效。

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

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

最初，您的实例处于 `pending` 状态，但在几分钟后将进入 `running` 状态。要查看有关您的实例的信息，请使用 `Get-EC2Instance` cmdlet。如果您有多个实例，则可以使用 `Filter` 参数按照预留 ID 筛选结果。首先，创建类型为 `Amazon.EC2.Model.Filter` 的对象。接下来，调用使用该过滤器的 `Get-EC2Instance`，然后显示 `Instances` 属性。

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

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

## 在 VPC 中启动 Spot 实例
<a name="new-ec2instance-spot"></a>

以下示例脚本在指定的子网中请求一个 Spot 实例。该安全组必须是您为包含指定子网的 VPC 创建的安全组。

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