我正在编写许多通过名称标签而不是 ID 来启动和停止 EC2 实例的函数。首先,我编写了一个报告功能,可以在下面找到。
Function Get-EC2InstanceReport{
If((Get-Module -Name AWSPowerShell).Name -ne 'AWSPowerShell'){
Throw 'AWSPowerShell module is not loaded'
}
Get-EC2Tag | `
Where-Object {$_.ResourceType -eq 'instance' -and $_.Key -eq 'Name'} | `
Select-Object @{Name='InstanceID'; Expression={$_.ResourceID}}, @{Name='Name'; Expression={$_.Value}}, `
@{Name='Status'; Expression={Get-EC2InstanceStatus -IncludeAllInstances $true -InstanceId $_.ResourceID | % {$_.InstanceState.Name}}}
}
并且启动实例的功能可以正常工作。
Function Start-EC2InstanceByName ([string]$Name){
If((Get-Module -Name AWSPowerShell).Name -ne 'AWSPowerShell'){
Throw 'AWSPowerShell module is not loaded'
}
[object]$EC2Instance = Get-EC2InstanceReport | Where-Object {$_.Name -eq $Name}
Try{
If($EC2Instance[0].Status -eq 'stopped'){
Start-EC2Instance -InstanceId $EC2Instance[0].InstanceId | Out-Null
Test-EC2InstanceStatus -Name $Name -EndState 'running'
}
Else{
$ErrorMsg = "EC2 instance " + $EC2Instance[0].Name + " is not in the stopped state. It is " + $EC2Instance[0].Status + "."
Throw $ErrorMsg
}
}
Catch{
$_
}
}
但是当使用类似的方法停止实例时,我得到一个错误。
Function Stop-EC2InstanceByName ([string]$Name){
If((Get-Module -Name AWSPowerShell).Name -ne 'AWSPowerShell'){
Throw 'AWSPowerShell module is not loaded'
}
[object]$EC2Instance = Get-EC2InstanceReport | Where-Object {$_.Name -eq $Name}
Try{
If($EC2Instance[0].Status -eq 'running'){
Stop-EC2Instance -Instance $EC2Instance[0].InstanceID | Out-Null
Test-EC2InstanceStatus -Name $Name -EndState 'stopped'
}
Else{
$ErrorMsg = "EC2 instance " + $EC2Instance[0].Name + " is not in the running state. It is " + $EC2Instance[0].Status + "."
Throw $ErrorMsg
}
}
Catch{
$_
}
}
错误可以在下面找到。
Stop-EC2Instance : No instances specified
At C:\GitProjects\DBA\aws-powershell-scripts\AWSFunctions.psm1:61 char:4
+ Stop-EC2Instance -Instance $EC2Instance[0].InstanceID | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Stop-EC2Instance], AmazonEC2Exception
+ FullyQualifiedErrorId : Amazon.EC2.AmazonEC2Exception,Amazon.PowerShell.Cmdlets.EC2.StopEC2InstanceCmdlet
任何帮助将不胜感激。如果您需要任何进一步的信息,请告诉我。
进一步的进展。
是的,没有解决为什么会发生错误并在亚马逊https://forums.aws.amazon.com/thread.jspa?threadID=143319上的 AWS 论坛上打开它
但是可以通过将函数更改为下面的函数来创建所需的行为。
Function Stop-EC2InstanceByName ([string]$Name){ If((Get-Module -Name AWSPowerShell).Name -ne 'AWSPowerShell'){ Throw 'AWSPowerShell module is not loaded' } [object]$EC2Instance = Get-EC2InstanceReport | Where-Object {$_.Name -eq $Name}
Try{
If($EC2Instance[0].Status -eq 'running'){
Get-EC2Instance -Filter @{Name="tag:Name"; Value=$Name} | Stop-EC2Instance | Out-Null
Test-EC2InstanceStatus -Name $Name -EndState 'stopped'
}
Else{
$ErrorMsg = "EC2 instance " + $EC2Instance[0].Name + " is not in the running state. It is " + $EC2Instance[0].Status + "."
Throw $ErrorMsg
}
}
Catch{
$_
}
}