There’s that old issue of VI connections not surviving
function calls – e.g. if I have a function initializing the VI session:
Is this be design, or just a side effect of something else?
Not being able to externalize connection code to another function is a
big inconvenience. I have stubled upon this when developing the
PowerGUI PowerPack and had to workaround the issue by storing the
connection in an array and then supplying it for each and every call to
any other cmdlet - very inconvenient.
Is this something you guys might consider fixing?
I am pretty sure this has to do with the scope of functions and scripts in Powershell. All actions are supposed to be local to the scope of the function so it doesn't interfere with other functions or the higher script environment. There is a way to refer to globals within a function $global:name or $script:name.
You might try doing
$global:MyVCServer=viconnect-server ...
Then refer to that object in other functions. Get-DataCenter -Server $global:myVCServer
Being a bit lazy, I do the connect-viserver before calling any functions, then that default global value is available within the functions
You can read up on scope in Powershell by typing the PS command help about_scope
You can also try $global:DefaultVIServer=viconnect-server .... This is the name of the default connection when you run connect-viserver from the shell.
SCampbell, luckily, Dmitry is a nice guy so he probably won't tease you for trying to teach a PowerShell MVP about scope. :smileysilly:
Unfortunately, it doesn't even work if you make the variable global. Been there, done that, bought the book, saw the movie.
I've had private conversations with c_shanklin about this topic and I understand it was something they did intend to address but don't recall the details. I imagine he'll enlighten us.
Author of the upcoming book: Managing VMware Infrastructure with PowerShell
Co-Host, PowerScripting Podcast (http://powerscripting.net)
Ouch!!
Thanks Hal, and a googleplex apologies Dmitry!!
I did a quick test before posting earlier, which might have been wrong, but this seems to work for me in VITK 1.0u1
function openVC { $global:MyVC=connect-viserver localhost } openVC get-datacenter -server $global:myVC
This is exactly the workaround I am using in PowerGUI right now, but as I mentioned, I would really like to see a more permanent solution in the toolkit.
Dmitry
I agree with Dmitry, this really is a pain, especially when trying to use it in PowerGui as you have to reference it each time
Do we know if this will be fixed in later versions ?
Thanks
Alan Renouf
Dmitri and Alan -
You're right to exepect that this will be addressed by a future version.
We're currently planning a future release and improving default server scope is part of its objectives. We haven't looked yet at the specific approach we should take so there isn't much detail to share at this point.
- Andrey