Retrieve Domain Name for Guest VMs using PowerCLI

I was recently required to return a collection of VMs and the domain to which they were a member. This was possible to retrieve by using the Get-VM cmdlet and manipulating the value of the ‘Guest.HostName property’.

By returning this value for a single VM we can see that it is possible to return the fully qualified domain name:

(Get-VM "server1").Guest.HostName
server1.domain.local

Now that we have this value it is possible to manipulate the string to obtain the information required.  By invoking the split operator to split the string into substrings we using the ‘\.’ as the delimiter pattern.

The escape character ‘\’  is required as ‘.’ matches any character except a new line.

(Get-VM "server1").Guest.HostName -Split '\.'

This would return the following output:

server1
domain
local

In order to retrieve the domain name we will require to remove the host name from the output, this can be performed by returning all the substrings after the first match.

$Domain = (Get-VM "server1" ).Guest.HostName -Split'\.'
$Domain[1..($Domain.Count)]

This would return the following output:

domain
local

All that is required now is for the substrings to be joined with the ‘.’ delimiter to generate the domain name:

$Domain = (Get-VM "server1").Guest.HostName -Split '\.'
$Domain[1..($Domain.Count)] -Join '.'

domain.local

This script can be run agaisnt a collection of VMs to return the VM name and the domain and to output to a file as below:

$VMs = Get-VM

$Output = ForEach ($VM in $VMs) 

    { 
    "" | Select @{N="Name";E={$VM.Name}},
    @{N="Domain";E={$Domain = $VM.Guest.HostName -Split'\.'
    ($Domain[1..($Domain.Count)] -Join'.').ToLower()}}
    } 
    
$Output = Export-CSV -Path D:\Output\VMDomainNames.csv -NoTypeInformation
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s