Automation

 View Only
  • 1.  How can I determine if a session is active?

    Posted Mar 01, 2008 07:18 PM

    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?



  • 2.  RE: How can I determine if a session is active?

    Posted Mar 05, 2008 01:55 AM

    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
    



  • 3.  RE: How can I determine if a session is active?

    Posted Mar 05, 2008 01:58 AM

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



  • 4.  RE: How can I determine if a session is active?

    Posted Mar 05, 2008 02:01 AM

    The trick is #your code here

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



  • 5.  RE: How can I determine if a session is active?

    Posted Mar 05, 2008 02:03 AM

    cool. thanks.



  • 6.  RE: How can I determine if a session is active?

    Posted Mar 05, 2008 02:03 AM

    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.



  • 7.  RE: How can I determine if a session is active?
    Best Answer

    Posted Mar 05, 2008 02:11 AM

    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.