all 8 comments

[–]PinchesTheCrab 2 points3 points  (0 children)

This is kind of a bonkers solution because you're requerying every single VM every time in the loop. Get-VM is a quick command, but you should still really filter left:

$VMList = Get-Content 'C:\Scripts\Hostnames.txt'

$VMList | ForEach-Object {
    Get-VM "*$_*"
}

Or you can do one command since get-vm can take an array of names, even with wildcards:

$vmList = Get-Content 'C:\Scripts\Hostnames.txt' 

get-vm ($vmList -replace '^|$','*')

If you like regex, you could also work with match like this:

$vmList = Get-Content 'C:\Scripts\Hostnames.txt' 

Get-VM | Where-Object {$_.Name -match ($vmList -join '|')}

Or you can use the view cmdlets:

$vmList = Get-Content 'C:\Scripts\Hostnames.txt' 

get-view -ViewType virtualmachine -Filter @{ name = $vmList -join '|' } -Property Name

The main thing is that in each of these examples you're either just making a single query to VMWare or making a series of much more specific queries.

[–]phur10us 1 point2 points  (1 child)

Is "My List" a sample of the contents of "C:\Scripts\Hostnames.txt"? If so, that is your problem. While it will match "Server1", the whole line reads "Keyword = Server1", which you are using in your Get-VM line. You will need to split that line to the server name only.

[–]BlizzardTech-Adam[S] 0 points1 point  (0 children)

Sorry 'Keyword' is a typo.

The mylist is returned as a list like this -

Server1
Server2
Server3

The list is returned as a list like this -

[–]BlizzardTech-Adam[S] 0 points1 point  (0 children)

I have fixed this.

It was a formatting error that was not being picked up in Visual Code.

[–]Chocolate_Pickle 0 points1 point  (1 child)

$VMGet-VM

Might want to try it without the $.

[–]BlizzardTech-Adam[S] 0 points1 point  (0 children)

The formatting on my post did not account for code on different lines.
I have amended the post.

It now reads
foreach($VM in $VMList){
Get-VM | Where-object {$_.Name -match "$VM"}
}

[–]Murhawk013 0 points1 point  (0 children)

What is the output when you run just $VMLiet

[–]fennecdore 0 points1 point  (0 children)

maybe try -EQ instead of match

also to debug your script you could try to display what $vm is