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?
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.
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
I give up on trying to format that thing. Anyway, that should work if you insert the appropriate line breaks.
The trick is #your code here
Remove the spaces between the {}'s and the keyword.
cool. thanks.
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.
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.