linux - 使用 "GetHostEntry"参数调用 "1"的异常 : "No such device or address"

标签 linux powershell scripting system-administration fqdn

这台机器的 FQDN:

thufir@dur:~$ 
thufir@dur:~$ hostname --fqdn
dur.bounceme.net
thufir@dur:~$ 

是的...正在工作 directly使用 powershell 给出 dur.bounceme.netFQDN 好的:

thufir@dur:~/powershell$ 
thufir@dur:~/powershell$ pwsh
PowerShell v6.0.1
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

PS /home/thufir/powershell> 
PS /home/thufir/powershell> [System.Net.Dns]::GetHostByName((hostname)).HostName                                        
dur.bounceme.net
PS /home/thufir/powershell> 

但是如果我想遍历一个数组怎么办?如何让 FQDN 显示为 dur.bounceme.net

thufir@dur:~/powershell$ 
thufir@dur:~/powershell$ ./hostname.ps1 
dur.bounceme.net
beginning loop
google.com
Exception calling "GetHostEntry" with "1" argument(s): "No such device or address"
At /home/thufir/powershell/hostname.ps1:14 char:3
+   $fqdn = [System.Net.Dns]::GetHostEntry($i).HostName
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ExtendedSocketException

google.com
localhost
end
thufir@dur:~/powershell$ 

脚本:

#!/usr/bin/pwsh -Command


#hostname is a reserved variable name?

[System.Net.Dns]::GetHostByName((hostname)).HostName


"beginning loop"

$hosts = ("google.com", "hostname", "localhost")

foreach($i in $hosts) {
  $fqdn = [System.Net.Dns]::GetHostEntry($i).HostName
  write-host $fqdn
}


"end"

我试过从 hostname 周围删除引号并在前面加上美元符号 $。这是保留字?

解释所涉及术语的加分点。

最佳答案

您将主机名用作字符串,而该字符串不在您的主机文件中,就像 localhost 一样,它将失败。

如果您使用默认的本地主机名,那么它们是:

'127.0.0.1'
$env:COMPUTERNAME
'localhost'

所以,你应该这样做

$TargetHosts = ('stackoverflow.com','google.com', $env:COMPUTERNAME,'localhost','127.0.0.1')

foreach($TargetHost in $TargetHosts) 
{ ( $fqdn = [Net.Dns]::GetHostEntry($TargetHost).Hostname ) }

stackoverflow.com
google.com
WS01
WS01
WS01

另请参阅这篇关于使用 native Resolve-DnsName cmdlet 与 .NET 库的帖子。

Why not just use the built-in DNS cmdlets? Or is there a particular reason you are traveling down the raw .Net path? Code project, homework assignment, curiosity?

powershell how to resolve name to IP address using Windows method

关于linux - 使用 "GetHostEntry"参数调用 "1"的异常 : "No such device or address",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821192/

相关文章:

linux - 如何在 linux mint 下的 zsh 中设置 virtualenvwrapper?

linux - Ubuntu 中的 Cron 作业

c# - Powershell 忽略通过 SessionStateProxy.SetVariable 传递的参数

Python脚本将编译但不会在maya中执行任何操作

linux - npm 安装失败,npm.cmd : command not found

linux - 无法通过 Composer 安装 Laravel 5.1,但可以在 5.2 上运行

powershell - 验证长度 Powershell

powershell - New-PSSession 在本地不起作用

python - 将 Bash 变量读入 Python 脚本

scripting - 从批处理中调用 PowerShell,并检索脚本中设置的临时环境变量的新值?