tags:

views:

747

answers:

1

I'm rather new to Powershell and am working on setting up my profile.ps1 file. I have a few managed DLLs that I use often to maintain processes throughout the day which I'd like to be able to load up with quick function calls. So I created this function in my ps1 file:

function LoadSomeDll
{
    [System.Reflect.Assembly]::LoadFrom("c:\wherever\SomeLib.dll")
    return new-object "SomeLib.SomeObject"
}

Then, in Powershell, I do this:

PS > $myLibInstance = LoadSomeDll

The problem is that $myLibInstance, though it appears to be loaded, doesn't behave the way I expect it to or if it would if I explicitly load it without the function. Say SomeLib.SomeObject has a public string property "ConnectionString" that loads itself (from the registry, yuck) when the object is constructed.

PS > $myLibInstance.ConnectionString
//Nothing returned

But, if I do it without the function, like this:

PS > [System.Reflect.Assembly]::LoadFrom("c:\wherever\SomeLib.dll")
PS > $myOtherLibInstance = new-object "SomeLib.SomeObject"

I get this:

PS > $myOtherLibInstance.ConnectionString
StringValueOfConnectionStringProperty

Why does this happen? Is there any way that I can return an instantiated new-object from a Powershell function?

Thanks in advance.

+5  A: 

The problem you're running into is that your original function is returning an array of objects, not a single object.

One of the tricks in PowerShell is understanding that in a function, every statement which evaluates no a non-void value will be written to the pipeline. The return "value" of a function is simply the contents of the pipeline.

The call to LoadFrom returns an assembly. So the actual return of the function LoadSomeDll is an array containing an assembly and an instance of your object. You're actually calling ConnectionString on the type Object[] and hence it silently fails.

Try switching the function to the following. I intentionally left off the keyword return because it's confusing in the context of powershell.

function LoadSomeDll
{
    [System.Reflect.Assembly]::LoadFrom("c:\wherever\SomeLib.dll") | out-null
    new-object "SomeLib.SomeObject"
}
JaredPar
Thanks again, JaredPar. You have been my Powershell savior over the last week.
AJ
@PITADev, you've essentially hit the same problems I hit in my early powershell days in almost the same order :). It's so counterintuitive at times.
JaredPar
+1 nice explanation. I've encountered this issue as well.
Richard Berg
Agreed - imo, the return keyword should not accept arguments. It should signify leaving a function, and nothing else.
x0n
+1 for x0n's comment. Allowing return to "appear" to return an object just results in confusion WRT how functions output objects.
Keith Hill