halr9000
Commander
Commander

How can I determine if a session is active?

Jump to solution

When writing scripts, I want to check at the top whether or not a session exists, and if not, prompt a user for credentials and server name in order to create one. I'd like to be able to do something like this:

if ($ViSession) { get-vm }

or

if (!Get-ViSession) { 
  Get-ViServer -server (read-host "Enter server name") 
}

So how will we be able to do this?

My signature used to be pretty, but then the forum software broked it. vExpert. Microsoft MVP (Windows PowerShell). Author, Podcaster, Speaker. I'm @halr9000
0 Kudos
1 Solution

Accepted Solutions
admin
Immortal
Immortal

Yeah...a Test-ViSession cmdlet could query the server, that would be cool.

Sure. Until then, I think this fits the bill. It's effectively doing the same thing.

View solution in original post

0 Kudos
6 Replies
admin
Immortal
Immortal

You can't tell if a session is still valid strictly from the client

since session management is owner by the server. Sessions may time out

or be killed by administrators. So the only way to tell is to initiate

a request to the server. We might want to add this as something we

explicitly support but given what you currently have available, you

could try something like:

function test-viserver {
  $needSession = $false

  $session = $null
  trap {
    Set-Variable needSession $true -Scope 1
    continue
  }

  Get-OSCustomizationSpec -name __foo__
  if ($needSession -eq $true) {
    $session = Get-VIServer -Server (Read-Host "Enter server name")

    if ($session -ne $null) {
      $needSession = $false
    }   
  }

  return !$needSession
}

And use it like this:

PS C:\> . test-viserver
Enter server name: junk
False
PS C:\> . test-viserver
Enter server name: server
True
PS C:\> . test-viserver
True

0 Kudos
admin
Immortal
Immortal

I give up on trying to format that thing. Anyway, that should work if you insert the appropriate line breaks.

0 Kudos
halr9000
Commander
Commander

The trick is #your code here

Remove the spaces between the {}'s and the keyword.

My signature used to be pretty, but then the forum software broked it. vExpert. Microsoft MVP (Windows PowerShell). Author, Podcaster, Speaker. I'm @halr9000
0 Kudos
admin
Immortal
Immortal

cool. thanks.

0 Kudos
halr9000
Commander
Commander

So the only way to tell is to initiate

a request to the server. We might want to add this as something we

explicitly support

Yeah...a Test-ViSession cmdlet could query the server, that would be cool.

My signature used to be pretty, but then the forum software broked it. vExpert. Microsoft MVP (Windows PowerShell). Author, Podcaster, Speaker. I'm @halr9000
0 Kudos
admin
Immortal
Immortal

Yeah...a Test-ViSession cmdlet could query the server, that would be cool.

Sure. Until then, I think this fits the bill. It's effectively doing the same thing.

View solution in original post

0 Kudos