这台机器的 FQDN
:
thufir@dur:~$
thufir@dur:~$ hostname --fqdn
dur.bounceme.net
thufir@dur:~$
是的...正在工作 directly使用 powershell
给出 dur.bounceme.net
的 FQDN
好的:
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
我是一名优秀的程序员,十分优秀!