Function Get-HVComputerName
{
[CmdletBinding()]
param(
[Alias("ServerName")][Parameter()]
$HVHostName = $env:COMPUTERNAME,
[Alias("ComputerName")][Parameter()]
[string[]]$VMName
)
#VMWare.VimAutomation.Core also has a "Get-VM" cmdlet,
#so unload that module if it's present first
If (Get-Module -Name VMware*) { Remove-Module -Name VMware* -Verbose:$false }
If (!(Get-Module -Name Hyper-V)) { Import-Module -Name Hyper-V -Verbose:$false }
$VMs = Get-VM -ComputerName $HVHostName -Name "*$VMName*"
If ($VMs)
{
$DNSNameArr = @()
If ($VMs.Count -gt 1)
{
Write-Host "`nFound the following VMs on Hyper-V server $HVHostName with name like `"`*$VMName`*`":" -ForegroundColor Green
$VMs.Name | Out-Default
Write-Host ""
}
ForEach ($VM in $VMs)
{
$Name = $VM.Name
If ($VerbosePreference -eq "Continue")
{
Write-Host ""
}
Write-Verbose "VM: $Name found on server $HVHostName"
If ($VM.State -ne "Running")
{
Write-Verbose "VM: $Name is not in a 'running' state. No IP address will be present.`n"
Continue
}
$VMNetAdapters = $VM | Select-Object -ExpandProperty NetworkAdapters
If ($VMNetAdapters)
{
Write-Verbose "VM $Name - Found the following network adapter(s)"
If ($VerbosePreference -eq "Continue")
{
$VMNetAdapters | Out-Default
}
ForEach ($NetAdapter in $VMNetAdapters)
{
$AdapterName = $NetAdapter.Name
$IPAddresses = $NetAdapter | Select-Object -ExpandProperty IPAddresses
If ($IPAddresses)
{
Write-Verbose "VM: $Name - Adapter: `"$AdapterName`" - Found the following IP address(es) on network adapter"
If ($VerbosePreference -eq "Continue")
{
$IPAddresses | Out-Default
}
ForEach ($IP in $IPAddresses)
{
$DNSName = $IP | Resolve-DnsName -Verbose:$false -ErrorAction SilentlyContinue
If ($DNSName)
{
$DNSFound = $true
$VMDNS = [PSCustomObject]@{
VMName = $Name
IP = $IP
DNSName = $DNSName.NameHost
}
$DNSNameArr += $VMDNS
}
Else
{
Write-Warning "VM: $Name - Adapter: `"$AdapterName`" - IP: $IP - No DNS name found"
Continue
}
}
If (!($DNSFound))
{
Write-Warning "VM: $Name - No DNS entries found for any associated IP addresses"
}
Else
{
$DNSFound = $false
}
}
Else
{
Write-Warning "VM: $Name - Adapter: `"$AdapterName`" - No IP address assigned to adapter"
Continue
}
}
}
Else
{
Write-Warning "VM: $Name - No Network adapters found"
Continue
}
}
If ($DNSNameArr)
{
If ($VerbosePreference -eq "Continue")
{
Write-Host ""
}
Return $DNSNameArr
}
Else
{
Write-Warning "No DNS names found for VM(s) with name like $VMName on server $HVHostName"
}
}
Else
{
Write-Warning "No VM found on server $HVHostName with name like $VMName"
}
} #End function Get-HVComputerName
2条答案
按热度按时间z8dt9xmd1#
你可以试试
获取虚拟机的IP地址并对其执行反向DNS查找。
uqcuzwp82#
这里的演示有点晚了,但是我采用了Greyula-Reyula非常有效的答案,并将其转换为一个函数,该函数可以提供更多反馈,说明为什么您可能无法从它获得输出。我对这一级别的脚本编写相对来说比较陌生,所以我相信有更有效的方法来完成此操作。但我是一个“冗长”的粉丝,我尽量让我的脚本对我自己来说尽可能容易理解,以防我以后想再把它们弄得一团糟。