billyjoel
Enthusiast
Enthusiast

Get VMs with name like - Script error

Jump to solution

Hi All,

I'm running the below script over different vcenters from the vcenters.txt file to get all VMs with "lb" in their names:

$vcenters = Get-Content vcenters.txt

$credential = Get-Credential -Message "Enter vCenter Credentials."

foreach ($vcenter in $vcenters){

    Write-Output "connecting to vcenter" $vcenter

    Connect-VIServer $vcenter -Credential $credential

  

   Get-VM |

    Select Name,PowerState,

    @{N='VMHost';E={$_.VMHost.Name}},

    @{N="vCenter";E={$_.Uid.Split('@')[1].Split(':')[0]}} | Where-Object {$_.name  -Like "*lb*"}

}

The problem is that it is going only thru the firts vcenter in the txt file several times, it list all the VMs with "lb" from the first vcenter in the txt file then at the end it's showing the below error:

connecting to vcenter

Connect-VIServer : Cannot validate argument on parameter 'Server'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

At C:\Users\user.lastname\Desktop\lb.ps1:9 char:22

+     Connect-VIServer $vcenter -Credential $credential

+                      ~~~~~~~~

    + CategoryInfo          : InvalidData: (:) [Connect-VIServer], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.ConnectVIServer

Then it starts and do the same.

What could I be doing wrong here?

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership

It looks like that could be caused by your .txt file.

Any blank lines in there?

What does the following return?

Get-Content vcenters.txt

(Get-Content vcenters.txt).Count


Does that Count correspond with the number of names you have in the .txt file?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
2 Replies
LucD
Leadership
Leadership

It looks like that could be caused by your .txt file.

Any blank lines in there?

What does the following return?

Get-Content vcenters.txt

(Get-Content vcenters.txt).Count


Does that Count correspond with the number of names you have in the .txt file?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
billyjoel
Enthusiast
Enthusiast

LucD​ you are right thanks there were 2 empty spaces at the end of the file, not sure how they got there.

I also I moved the below out of the loop Smiley Happy

  1. Get-VM | 
  2.     Select Name,PowerState, 
  3.     @{N='VMHost';E={$_.VMHost.Name}}, 
  4.     @{N="vCenter";E={$_.Uid.Split('@')[1].Split(':')[0]}} | Where-Object {$_.name  -Like "*lb*"}
0 Kudos