I have created a C# project in Visual Studio and I am looking at the best way to access this in PowerShell.
I created the project to produce a dll. I can access this fine in visual studio by running:
test.Class1.find(“username”, “password”, “type”, “id”)
but when I import the dll in PowerShell I don’t have access to the find to run the command.
Do I have to change the visual studio project to allow PowerShell access?
Hi Paul! Without looking at the code, I assume that the problem may be with access modifiers for your class. In C# if you don’t explicitly define your top class to be public, it is created with internal scope. If it is defined as public, maybe the method is not.
If that doesn’t help, please paste an sample of your code and I’ll take a closer look.
Looks fine to me. Once you’ve loaded up your DLL (with Add-Type -Path c:\your\dllfile.dll), you should be able to do: [test.Class1]::find($username, $password, $type, $id)
Perfect! I was trying to call the find incorrectly.
One last question - the c# code ends with a Console.WriteLine which appears on screen in PowerShell. is there a way to capture this in PowerShell value? I tried
$test = [test.Class1]::find($username, $password, $type, $id) but this didn’t work.
Not really. Console.WriteLine() is kind of like C#'s version of Write-Host. It writes to the console, and doesn’t provide data in any sort of return value or parameter that the code can inspect later. (This also may cause a problem if your DLL were ever to be used in a non-console application, such as the PowerShell ISE.)
Yeah, I agree with Dave. You’ll have to call it as [test.Class1]::find(“username”, “password”, “type”, “id”) because that’s how static members of classes are invoked in PowerShell.
If you had some non-static methods, you would have to instantiate an object of Class1 type as follows:
$MyObject = New-Object -Type test.Class1
)
And then you be able to access those methods like that:
Paul, can you can update your method to return string instead of a void? PowerShell is object oriented, so if you’re doing some crazy property value concatenation within your C# code to produce a string just to be able to pass it over to PowerShell, you may want to pass that initial object instead.
Can you do that? Sure. But now you’re getting into questions of class design, where it’s more about coding style (object oriented vs functional, etc), making a pleasant API, etc. In C#, I would probably lean away from having one class function return a cookie container, then require a caller to pass that container right back in as a parameter to another method.
Instead, I’d probably use non-static methods, and have each instance of the object keep track of the cookie container via a field and/or property. It may not even be necessary to have that field be public, if your class already covers all the uses of the container.