Powershell脚本从计算机列表中获取外部IP地址

时间:2017-02-13 18:12:07

标签: loops powershell ip

我一直在尝试使用此脚本来获取网络上多台计算机的外部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
}

1 个答案:

答案 0 :(得分:2)

您需要使用cmdlet或参数指定远程执行。 $computer本身只是一个带字符串值的变量。

某些cmdlet支持-ComputerName $computer参数,而其他像Invoke-RestMethod则要求您使用Invoke-Command或类似内容运行它们。

实施例

$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