简体   繁体   中英

Powershell Script to get external IP address from a list of computers

I have been trying to get this script to get the external IP address of multiple machines on my network. So far, the script seems to iterate through the loop but run the command on my local machine rather than the remote one on the loop.

$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
}

You need to use a cmdlet or parameter to specify remote execution. $computer by itself is just a variable with a string-value.

Some cmdlets support a -ComputerName $computer paramter, while others like Invoke-RestMethod require that you run them using Invoke-Command or something similar.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM