尝试仅从主机名返回ipv4地址

时间:2018-12-10 18:08:37

标签: powershell

所以我的代码看起来像这样

Write-Host "TECH ID's `n Ador: 1`n Len: 2 `n Colleen: 3 `n Angel: 4 `n Simon: 5 `n Brian: 6`n Jennifer : 7 `n Tina 8 `n"
$tech_name = Read-Host -Prompt "Please enter Tech ID or IP"
Write-Host "Please Wait, Do not click or type anything."
& "M:\Forms\1 FS Remote\FS_remoteassistance.exe"
Sleep 3

$ping = New-Object System.Net.NetworkInformation.Ping
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate("C:\Windows\system32\cmd.exe")
Sleep 2
if ($tech_name -eq "brian" -or $tech_name -eq "6" ){
    $wshell.SendKeys($($ping.Send("xxxxx").Address).IPAddressToString)
    $wshell.SendKeys("~")
}
Elseif ($tech_name -eq "angel" -or $tech_name -eq "4"){
    $wshell.SendKeys($($ping.Send("xxxxx").Address).IPAddressToString)
    $wshell.SendKeys("~")
    }
Elseif ($tech_name -eq "len" -or $tech_name -eq "2"){
    $wshell.SendKeys($($ping.Send("xxxxx").Address).IPAddressToString)
    $wshell.SendKeys("~")
    }
Elseif ($tech_name -eq "colleen" -or $tech_name -eq "3"){
    $wshell.SendKeys($($ping.Send("xxxxx").Address).IPAddressToString)
    $wshell.SendKeys("~")
    }
Elseif ($tech_name -eq "ador" -or $tech_name -eq "1"){
    $wshell.SendKeys($($ping.Send("xxxxx").Address).IPAddressToString)
    $wshell.SendKeys("~")
    }
Elseif ($tech_name -eq "simon" -or $tech_name -eq "5"){
    $wshell.SendKeys([System.Net.Dns]::GetHostAddresses("")[0])
    $wshell.SendKeys("~")
    }
Elseif ($tech_name -eq "7"){
    $wshell.SendKeys($($ping.Send("xxxxx").Address).IPAddressToString)
    $wshell.SendKeys("~")
    }
Elseif ($tech_name -eq "8"){
    $wshell.SendKeys($($ping.Send("xxxxxx").Address).IPAddressToString)
    $wshell.SendKeys("~")
    }
Else{
    $wshell.SendKeys($tech_name)
    $wshell.SendKeys("~")
    }

因此,此脚本的目标是获取主机名并返回ipv4地址,以便客户端可以运行该程序并连接到技术人员而无需知道其ip地址。问题是我只需要发送ipv4地址,但在某些计算机上需要发送ipv6,而在其他计算机上需要发送ipv4。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我不知道您为什么使用两个不同的调用来获取IP,但这将返回命名系统的IPv4 ...

[System.Net.Dns]::GetHostAddresses($env:COMPUTERNAME).
    Where({$_.AddressFamily -eq 'InterNetwork'}).
    IPAddressToString

$env:COMPUTERNAME替换为目标系统名称,而otta会为您提供所需的内容。 [咧嘴]

以上要求ps4 +使用.Where()数组方法。这是一种使用管道和Where-Object技术的方法。它应该在ps2上工作,但是我无法测试。

([System.Net.Dns]::GetHostAddresses($env:COMPUTERNAME) |
    Where-Object {$_.AddressFamily -eq 'InterNetwork'}).
    IPAddressToString