VMware Cloud Community
hugopeeters
Hot Shot
Hot Shot

Check whether connected to Virtual Center

Hi,

A question for my fellow VI Toolkit enthusiasts:

Can you think of a way to check whether or not you already connected to Virtual Center?

The reason I ask, is because I have created a number of functions that I want to place in the default profile for all my colleagues. The functions use the VI Toolkit and I don't want each function to have it's own connect / disconnect. Especially for a function that can be used against a collection of objects (e.g.: Get-QADComputer | % { My-Function $_.Name } ).

I am looking at trying to execute a Get-Datacenter, for instance, and then check if that succeeded using the automatic variable $?. The problem is that Get-Datacenter -ErrorAction SilentlyContinue still echoes back a big, fat, red error on screen. That I don't like.

Any thoughts are welcome.

Hugo

www.peetersonline.nl

Reply
0 Kudos
4 Replies
Adidas6
Contributor
Contributor

Try this:

if ($DefaultVIServer -eq $null) {get-vc yourserverhere}

at the start of your script.

LucD
Leadership
Leadership

The variable $DefaultVIServer is not reset after a Disconnect-VIServer.

So that doesn't really solve the problem I'm afraid.


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

Reply
0 Kudos
hugopeeters
Hot Shot
Hot Shot

It does help, so thanks!

Any other thoughts are welcome.

Reply
0 Kudos
RicardoMalta
Contributor
Contributor

Hi,

I couldn't find a way to checkt it, so I used a command that quickly tells me if I'm connected or not Smiley Wink

Get-LogType returns the log files from the VC or ESX host. It takes only a second or two to return.

In a login-function I use this code to connect, reconnect or reuse the CONNECTION

if ($VCServer) {
    trap {
        Write-Host "Current connection invalid"
        continue
    }
    $check = Get-LogType -ErrorAction SilentlyContinue

    if ($check) {
        Write-Host "Still connected ..."
    } else {
        Write-Host "Reconnecting ..."
        trap {
            Write-Host "  Current saved session invalid"
            continue
        }
        $rc = Connect-VIServer -Server $VIServer -Session $VCServer.SessionId
        if (! $rc) {
            Remove-Variable VCServer
        }
    }
}

if (!$VCServer) {
    Write-Host "Connecting ..."
    $VCServer = Connect-VIServer -Server $VIServer -Credential $credential
} 

I hope this can help you, at least as a bypass

Regards,

Ricardo

Reply
0 Kudos