简体   繁体   English

使用Powershell从FQDN获取域名

[英]Get Domain name from FQDN with powershell

I had been looking for a short code to do this for a while and finally figured it out myself. 我一直在寻找一段简短的代码来执行此操作,最后自己弄清楚了。 Thought I would share it. 以为我会分享。

$FQDN = "madeup.name.domain.co.in"

I would need the result as name.domain.co.in 我需要将结果作为name.domain.co.in

An arguably cleaner solution would be 可以说更清洁的解决方案是

$FQDN.Substring($FQDN.IndexOf(".") + 1)

This gets the substring of $FQDN starting after the first . 这将获取$FQDN的子字符串,从第一个字符串开始. .

Code: 码:

$hostname = $FQDN.Split('.')[0]
$Domain = $FQDN -replace "$hostname.",""

$Domain will have the result. $Domain将得到结果。

Hope this helps 希望这可以帮助

If you want to get the "registrableDomain" you can use this function: https://github.com/ili101/PowerShell/blob/master/Get-Domain.ps1 如果要获取“ registrableDomain”,则可以使用以下功能: https : //github.com/ili101/PowerShell/blob/master/Get-Domain.ps1

Get-Domain madeup.name.madeup.domain.co.in

Output: domain.co.in 输出:domain.co.in

I like this approach from @Rohin Sidharth: 我喜欢@Rohin Sidharth的方法:

$hostname = $FQDN.Split('.')[0]
$Domain = $FQDN -replace "$hostname.",""

You can also get the $hostname from the $env variable: 您还可以从$ env变量获取$ hostname:

$env:computername 

If you are running on the server in question, then the replace mechanism will provide the domain even if the name of the server has a '.' 如果您在有问题的服务器上运行,那么即使服务器名称带有“。”,替换机制也将提供域。 in it. 在里面。

Regex , to return first segment composed of Letter, digit, '-' and '_' 正则表达式 ,返回由字母,数字,“-”和“ _”组成的第一段

"made-up1.name.madeup.domain.co.in" -replace('(^[\w-_\d]+)\.(.*)','$1')

return made-up1 退货made-up1

DomainName with $2 域名为$ 2

"made-up1.name.madeup.domain.co.in" -replace('(^[\w-_\d]+)\.(.*)','$2')

return name.madeup.domain.co.in 返回name.madeup.domain.co.in

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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