我正在编写一些用于通过名称标记而不是ID来启动和停止EC2实例的函数。首先我写了一个报告功能,可以在下面找到。将属性从对象传递给Stop-EC2Instance cmdlet时出错
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
任何帮助将不胜感激。如果您需要更多信息,请告诉我。
进一步进展。
权利,而不是解决为什么出现错误,并且有对AWS论坛在亚马逊https://forums.aws.amazon.com/thread.jspa?threadID=143319
但所期望的行为开放可以通过改变功能到低于被创建。
功能停止-EC2InstanceByName([字符串] $名称){ 如果((GET-模块-Name AWSPowerShell)请将.Name -ne 'AWSPowerShell'){ 掷 'AWSPowerShell模块没有装载' } [对象] $ EC2Instance = Get-EC2InstanceReport |位置对象{$ _。名称-eq $名称}
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{
$_
}
}
嗨,谢谢你。奇迹般有效。 –