Getting the 'value' of get-vm without headers

Hi-

I have a code snippet below from inside a function:

Write-Host "Displaying VM's on host: " $vchost -ForegroundColor Green
$script:VCHostVMs = get-vmhost -name $vchost | get-vm | Select Name,@{N='GuestOS';E={$_.GuestID}} | ft
$script:VMvalue = get-vmhost -name $vchost | get-vm | Select Name -ExpandProperty Name
$cnt = [pscustomobject]@{ VMCount = (Get-VMHost -Name $vchost | Get-VM).Count }
$fcount = $cnt.vmcount
write-host "Total number running VMs= " -NoNewline
$fcount
}

I want to display a list of VM’s on a host with formatted output which the first get-vm ($VCHostVMs) does. This is so the user can see what VM’s are on the host (User will be prompted later in the script to enter a VM name). Then I do a second get-vm to another variable ($VMvalue) so I can use

-expandproperty to strip the variable of it’s headers. Then I can do a compare on just the VM name to see if the user entered a VM that exists. I was just curious if there is a cleaner way to do this with just one get-vm? Don’t need to write the code for me, just give me some hints, tyvm.

 

…ar

Get-VM | Format-Table -HideTableHeaders -Property Name

Or remove ft at the end of line 2 and try this

$VCHostVMs.Name

Would any of these work? I’m not sure if I understand your request.

Also, if you already have the $VCHostVMs variable, you could simply reuse it to set the $VMvalue variable.

$script:VCHostVMs = get-vmhost -name $vchost | get-vm | Select Name,@{N='GuestOS';E={$_.GuestID}}
$script:VMvalue = $VCHostVMs | Select Name -ExpandProperty Name

 

This is essentially what I used:

}
Write-Host "Displaying VM's on host: " $vchost -ForegroundColor Green
$script:VCHostVMs = get-vmhost -name $vchost | get-vm | Select Name,@{N='GuestOS';E={$_.GuestID}} | out-default
$script:VCHostVMs
$script:VMvalue = $VCHostVMs | Select Name -ExpandProperty Name
$cnt = [pscustomobject]@{ VMCount = (Get-VMHost -Name $vchost | Get-VM).Count }
$fcount = $cnt.vmcount
write-host "Total number running VMs= " -NoNewline
$fcount

I was not sure about re-using the variable since it had other properties previously enumerated. I had to add the ‘out-default’ or else it would not output correctly. Thanks.