I am attempting to get only the hostname portion only of my esx server list from VC
$vmhosts = get-vmhost -Location (get-cluster -name "TestCluster") | Select-Object Name
And that returns:
Name ---- server1.mydomain.com server2.mydomain.com server3.mydomain.com
What I would like returned is only the hostname portion of the name.
I still do not fully understand the pipelining and manipulating object to get the correct syntax correct. I have a few different thinks, usually ending up with Method invocation failed... and Expressions are only permitted as the first element....
I can get the hostname portion by doing something like this:
$myvar="server1.mydomain.com" Write-host $myvar.substring(0,($myvar.indexof(".")))
How do I, or is there a way to, incorporate the above (something better) into original pipeline so that I only get a list of hostnames?
You can use the ForeEach-Object cmdlet and a regex to extract the hostnames.
$vmhosts = get-vmhost -Location (get-cluster -name "TestCluster") | %{([regex]"(\w+)").Match($_.Name).Groups[1].Value}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
You can use the ForeEach-Object cmdlet and a regex to extract the hostnames.
$vmhosts = get-vmhost -Location (get-cluster -name "TestCluster") | %{([regex]"(\w+)").Match($_.Name).Groups[1].Value}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Excellent, thanks Luc,
Just a follow up question to aid in understanding. What is the rationale around using the Groups[0].Value rather than just .Value?
Is there some significance to the Groups over Value?
No, not in this case.
But it's a habit of mine to use the Groups notation since this is the format you would have to use in any case should you look for 2 or more sub-expressions.
The Value property always returns the match of the complete regex expression.
Suppose you would also like to extract the last qualifier of the FQDN, then your regex would be something like this: "(\w).\.(\w+)".
In this case the Value property would return the complete FQDN.
Both sub-expressions would be: Groups\[1\].Value and Groups\[2\].Value.
For further info on regular expressions have a look at Tobias's Mastering PowerShell article.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
that makes sense to me, i'll take note of that for future scripts
Again, thanks