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