03.18.2009
We were working recently to align our guest VM object names with their DNS names. As we have over 800 guests, this would have taken us a while to compile by hand. I wrote the following PowerShell script to flag machines where the hostname differs from the object name.
# Get all of the VMs as an object
$objVMs = Get-VM
# Loop through all of the VMs
ForEach ($objVM in $objVMs){
# Get the VM Guest object (which contains the DNS information)
$objGuest = Get-VMGuest -VM $objVM
# Set a variable to the VM object name
$objVMName = $objVM.Name
# Set a variable to the DNS name
$objVMFQDN = $objGuest.Hostname
# Sometimes the FQDN is empty or blank, so we screen those out with an "If not equals"
If (($objVMFQDN -ne "") -and ($objVMFQDN -ne $null)){
# The host name is the first part of the FQDN, so we split it, and take the first (0) segment as our host name
$objVMHostName = $objVMFQDN.split('.')[0]
}
Else {
$objVMHostName = $null
}
# Check that the host name is not null, and if the hostname does not match the VM name, echo the results
If (($objVMHostName -ne $null) -and ($objVMName -notlike $objVMHostName)){
# Write the results on one line, the VM object name, then the host name in square brackets. The "`" is an escape character
Write-Host $objVMName `[$objVMHostName`]
}
}
This worked perfectly. While I could have extended the script to rename these machine objects to the hostname, it was safer to look at each one individually. Even so, the script saved us a few hours of tedious work.
Comments
Leave a Reply
Jeffrey Snover on 03.19.2009
You made my day with this one. This is exactly the sort of utility script that we expected people to be able to put together quickly and save a ton of time.
Now that you wrote the script and shared it – everyone else can benefit from your skill and insight and they all owe you a debt of thanks.
Now that you have a script, you can run it via the task scheduler as often as you want (in V2 you can have the results emailed to you with the Send-MailMessage command) and never let your systems go out of spec for very long.
Nice work!
Experiment! Enjoy! Engage!
Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
Ben on 04.30.2010
Alan Renouf’s posted a much better script which does the same thing over on his blog.