PowerShell fails to call a simple function from an ASP.NET DLL
I'm trying to call this really simple .NET 4 function with PowerShell v2. Its definition look like:
Public Shared Function currentSchoolYear() As String Member of NM4.SiteAdmin.Logic.Subscription
Let's add the path to the DLL file containing that function. It's an ASP.NET MVC web application DLL file.
PS > Add-Type -Path C:\xxx\bin\xxxWebApp.dll
Let's try it (FAIL!):
PS >
[NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear() Exception calling "currentSchoolYear" with "0" argument(s): "The type initializer for 'NM4.SiteAdmin.Logic.Subscription' threw an exception." At line:1 char:54 + [NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException
Let's observe the class from PowerShell:
PS >
[NM4.SiteAdmin.Logic.Subscription] IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False Subscription System.Object
Let's observe the function from PowerShell
PS >
[NM4.SiteAdmin.Logic.Subscription]::currentSchoolYear MemberType : Method OverloadDefinitions : {static string currentSchoolYear()} TypeNameOfValue : System.Management.Automation.PSMethod Value : static 开发者_StackOverflowstring currentSchoolYear() Name : currentSchoolYear IsInstance : True
Why oh why? It seems like the doc to me.
I used this command to get more details about the error:
$error | Format-List -force
Which then throwed this more precise example:
System.NullReferenceException: Object
reference not set to an instance of an
object.
at
NM4.SiteAdmin.GlobalFunctions.EstMachineProduction()
in
C:\xxx\Old_App_Code\DataModel\GlobalFunctions.vb:line
17
And I discovered it was a call to the web.config that failed:
Return
ConfigurationManager.ConnectionStrings.Item("test_DBNM4").ConnectionString
DLL files loaded by PowerShell are probably not in their usual web context. I hardcoded a ConnectionString to test it (temporary, not a good security practice), and it's working.
It sounds like an exception in the static constructor OR a type on which NM4.SiteAdmin.Logic.Subscription depends could not be loaded. I'm assuming "C:\xxx\bin\xxxWebApp.dll" and friends aren't in GAC and you're not running from "C:\xxx\bin\" so therefore powershell can't resolve the dependencies. Try running this from "C:\xxx\bin\".
精彩评论