Reply to Message

View discussion in a popup

Replying to:
mazdajai
Contributor
Contributor

for loop on vcenters - list skipping on fail

I have a for loop get-vm statement against a list of vcenters with try/catch. For some reason when one of the vcenter fails, the remaining will fail and will not run.

Sample list of vcenters.inputs:

BadVC1

GoodVC1 <---will not run if BadVC1 fails

GoodVC2<---will not run if BadVC1 fails

$pwd='d:\';

$vcenters=gc vcenters.input | sort;

$invuser='xxx';

$invpass='xxx';

$outlog="$(Get-Date -uformat %m%e%g)_run.log";

$errlog='error.log';

"Time :: host :: Runtime (seconds)" | Out-file -Encoding UTF8 $outlog

"$MyInvocation.MyCommand.Definition" | Out-file -Encoding UTF8 $errlog

foreach ($vcenter in $vcenters) {

    $startsec=Get-Date

    $outfile=$vcenter+"_inv.csv"

try

{

    connect-viserver $vcenter -User $vcenter\$invuser -Password $invpass

    $Report = @()

       

    Get-VM | % {

        $vmcls = $_ | Get-Cluster

        $vmnet = $_ | Get-NetworkAdapter

        $vmds = $_ | Get-Datastore

        $vms = "" | Select-Object Cluster, Host, Name, FQDN, State, OS, Network, Memory, CPU, ServerRole, `

        PatchGroup, DataStore, ProvisionedGB, ConsumedGB, Contact, PVU, Replicated, Notes

        $vms.Cluster = $vmcls.Name

        $vms.Host = $_.VMHost   

        $vms.Name = $_.Name

        $vms.FQDN = $_.Guest.HostName

        $vms.State = $_.PowerState

        $vms.OS = $_.Guest.OSFullName

        $vms.Network = $vmnet.NetworkName

        $vms.Memory = $_.MemoryMB

        $vms.CPU = $_.NumCpu

        $vms.ServerRole = $_.CustomFields.Item("ServerRole")

        $vms.PatchGroup = $_.CustomFields.Item("PatchGroup")

        $vms.DataStore = $vmds.Name

        $vms.ProvisionedGB = $_.ProvisionedSpaceGB

        $vms.ConsumedGB = $_.UsedSpaceGB

        $vms.Contact = $_.CustomFields.Item("System Contact")

        $vms.PVU = $_.CustomFields.Item("PVU")

        $vms.Replicated = $_.CustomFields.Item("Replicated")

        $vms.Notes = $_.Notes

        $Report += $vms

       }

    $Report | ConvertTo-csv | Out-file -Encoding UTF8 $pwd\data\$outfile

    Disconnect-VIServer $vcenter -confirm:$false

    $endsec=Get-Date;

    "$(Get-Date -uformat %H:%M:%S) :: $vcenter :: $((New-TimeSpan -Start $startsec -End $endsec).TotalSeconds)" | Out-file -Encoding UTF8 -Append $outlog

}

catch

{

"$(Get-Date -uformat %H:%M:%S) :: $vcenter :: EXCEPTION" | Out-file -Encoding UTF8 -Append $outlog

$error | Out-file -Encoding UTF8 -Append $errlog

}   

};

Reply
0 Kudos