Powershell脚本从计算机列表中获取外部IP地址
我一直试图让此脚本获取我的网络上多台计算机的外部IP地址。到目前为止,脚本似乎遍历循环,但在本地机器上运行命令而不是循环中的远程命令。Powershell脚本从计算机列表中获取外部IP地址
$computers = get-content "c:\scripts\scriptdev\Addresses.txt"
$outfile ="c:\scripts\scriptdev\test2.csv"
$results = @()
foreach ($computer in $computers)
{
Invoke-RestMethod http://ipinfo.io/json | Select -exp ip $computer
Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name $computer
}
您需要使用cmdlet或参数来指定远程执行。 $computer
本身就是一个带有字符串值的变量。
一些cmdlet支持-ComputerName $computer
参数,而另一些像Invoke-RestMethod
则要求您使用Invoke-Command
或类似的东西运行它们。
Ex。
$computers = get-content "c:\scripts\scriptdev\Addresses.txt"
$results = @()
foreach ($computer in $computers)
{
$results += Invoke-Command -HideComputerName -ComputerName $computer -ScriptBlock {
New-Object -TypeName psobject -Property @{
Name = Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name
ExternalIP = Invoke-RestMethod http://ipinfo.io/json | Select -ExpandProperty ip
}
}
}
$results
谢谢,这有很大的帮助。你知道我可以如何移除产生的runspaceid区域? –
'$ results |选择对象名称,外部IP' –
记住标记为答案,如果这解决了你的问题,所以问题将被标记为关闭。 –
不清楚。您从不“问”任何cmdlet是否可以远程执行......不会使用'$ results'和'$ outfile'。你输入'$ computer'作为'Select-Object'的列名,这将使它产生具有它们自己属性的对象(不只是值)。 –
*我的网络上多台机器的外部IP地址* - 除非你肯定地知道这是在您的网络中简单配置的,没有确定的单个外部IP地址的计算机。可能存在多个外部IP地址的原因很多 - 多个WAN连接,不同的策略取决于谁登录或一天中的时间,不同的协议的不同路由,不同的入站服务(HTTPS,SSH)的多个IP。 。 – TessellatingHeckler