Hi all,
I have the below script to connect to different vcenters from a txt file and retrieve any VM containing the word "test" in it's name
$vcenters = Get-Content vcenters.txt
$credential = Get-Credential -Message "Enter vCenter Credentials."
$machine = Get-VM |
Select Name,PowerState,
@{N='VMHost';E={$_.VMHost.Name}},
@{N='IP';E={$_.Guest.IPAddress -join '|'}} | Where-Object {$_.name -Like "*test*"}
foreach ($vcenter in $vcenters){
Write-Output "connecting to vcenter" $vcenter
Connect-VIServer $vcenter -Credential $credential
if($machine){
$machine
}
else{
Write-Output "No VM containing test was found"
}
}
The problem is that right after I enter the credentials it shows the below error:
PowerCLI C:\Users\name.lastname\Desktop> .\test.ps1
Get-VM : 4/29/2020 5:33:10 PM Get-VM You are not currently connected to any servers. Please connect first using a Connect cmdlet.
At C:\Users\oscar.salas\Desktop\dban.ps1:3 char:12
+ $machine = Get-VM |
+ ~~~~~~
+ CategoryInfo : ResourceUnavailable: (:) [Get-VM], ViServerConnectionException
+ FullyQualifiedErrorId : Core_BaseCmdlet_NotConnectedError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM
Then it start to connect to each vcenters followed by the message
"No VM containing test was found"
I know for a fact that there are vms with "test" in their names but the outputs are:
"No VM containing test was found"
What could I be doing wrong here?
Move the following inside the loop below the ‘connect-Viserver’ $machine = Get-VM | Select Name,PowerState, @{N='VMHost';E={$_.VMHost.Name}}, @{N='IP';E={$_.Guest.IPAddress -join '|'}} | Where-Object {$_.name -Like "*test*"}
Move the following inside the loop below the ‘connect-Viserver’ $machine = Get-VM | Select Name,PowerState, @{N='VMHost';E={$_.VMHost.Name}}, @{N='IP';E={$_.Guest.IPAddress -join '|'}} | Where-Object {$_.name -Like "*test*"}
Thanks jpsider it's working now