0

我创建了一个 Powershell 脚本,该脚本将在 Task Scheduler 中运行,以根据我的公共 IP 地址更新我的 AWS 安全组。当我运行此脚本时,我收到一条错误消息,该消息发布在下面。

我还希望您能帮助我修改下面的脚本,以便在更新到新 IP 地址时删除旧 IP 地址。

剧本

# to get current ip address in cidr format 

$ipinfo = Invoke-RestMethod http://ipinfo.io/json

$ipinfo.ip | out-file -filepath currentip -NoNewline

$ipCidr = Add-Content -Path "currentip" -Value "/32"     

# take current ip address and update the security group 
# the second part I am getting an error message pasted below 

$ipchange =  @{ IpProtocol="tcp"; FromPort="1433"; ToPort="1433"; IpRanges=$ipCidr}

Grant-EC2SecurityGroupIngress -GroupId sg-0d28d1cbc04d5df91 -Region us-east-2 -IpPermission @($ipchange)

错误

<# Grant-EC2SecurityGroupIngress:无法绑定参数“IpPermission”。无法创建“Amazon.EC2.Model.IpPermission”类型的对象。“System.Management.Automation.PSObject”类型的对象无法转换为“System.Collections.Generic.List`1[System.String]”类型。在 C:\users\inayet\desktop\aws-amazon\scripts\runCurrentIP.ps1:15 char:93 + ... pId sg-0d28d1cbc04d5df91 -Region us-east-2 -IpPermission @($ipchange) + ~~~ ~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Grant-EC2SecurityGroupIngress], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Amazon.PowerShell.Cmdlets.EC2.GrantEC2SecurityGroupIngressCmdlet #>

4

3 回答 3

0

该错误消息似乎表明 cmdletGrant-EC2SecurityGroupIngress需要一个类型的对象,Amazon.EC2.Model.IpPermission并且它无法根据您传递的参数构造一个对象。

您的代码中可能有一行可能解释该错误:

$ipCidr = Add-Content -Path "currentip" -Value "/32"

不返回任何内容Add-Content,它只向文件添加行,因此$ipCidr此时不包含任何内容。

你可能想试试

$ipCidr = Get-Content -path "currentip"

在继续填充哈希表之前:

$ipchange =  @{ IpProtocol="tcp"; FromPort="1433"; ToPort="1433"; IpRanges=$ipCidr}

@()您放置的数组语法$IpRanges也不是必需的,并且可能也是您收到的错误消息的主要贡献者。

Grant-EC2SecurityGroupIngress -GroupId sg-0d28d1cbc04d5df91 -Region us-east-2 -IpPermission $ipchange

现在IpRanges成员不再为空,powershell 或许可以将其转换为Amazon.EC2.Model.IpPermission.

于 2018-08-26T13:57:08.587 回答
0

要解决类型转换错误消息,请在 add-content 行下方添加此代码。

$ipCidr = $ipCidr -as [int]

您所说的是您希望将存储在 $ipCidr 中的字符串值转换为整数值。

现在出现另一个问题是变量 $ipCidr = Add-Content -Path "currentip" -Value "/32" -NoNewline 没有输出值。

当我 cat currentip 时,我得到了正确的 ip cidr 地址,但是当我输出 $ipCidr 的值时,文件为空,并且我收到以下错误消息“您不能在空值表达式上调用方法。”

如何将存储在 currentip 文件中的整数值存储到变量 $ipCidr 中?

于 2018-08-26T12:48:55.847 回答
0

感谢大家的贡献!!!

这是我遇到的问题的解决方案。

# to get current ip address in cidr format

$ipinfo = Invoke-RestMethod http://ipinfo.io/json

$ipinfo.ip +"/32" | out-file -filepath currentip -NoNewline

$ipCidr = Get-Content -Path currentip

$ipchange = @{ IpProtocol="tcp"; FromPort="1433"; ToPort="1433"; IpRanges=$ipCidr} $ipchange

Grant-EC2SecurityGroupIngress -GroupId sg-123456789 -Region us-east-2 -IpPermission $ipchange

于 2018-08-28T21:34:01.220 回答