LaPhi
LaPhi

Reputation: 431

Is it possible to create a string in C# and use it with PowerShell?

Is it possible to create a string in a C# .exe and use this string in PowerShell?

Upvotes: 3

Views: 326

Answers (4)

Keith Hill
Keith Hill

Reputation: 201662

In the event you are hosting PowerShell within a C# app and you want to access a string variable defined in C# from the PowerShell script that you run, here's how to do that:

string foo = "some string defined in C# to be used in PowerShell";
runspace.SessionStateProxy.SetVariable("foo", foo);

You can then reference this variable in your PowerShell script as $foo.

Upvotes: 4

Philip Rieck
Philip Rieck

Reputation: 32568

Yes.

Your question is quite vague - are you using a powershell script to create an object from the c# assembly, then using that object? If so, simply set a property to the string you want and access it as normal from powershell.

Or, if it's a static method, you can just call it

   [My.Assembly.Type]::GetSomeString()

If you are running the c# exe, you can simply output it with writeline and powershell will pick it up:

.\myexe.exe > $someVar

Or, you can write it as a cmdlet, and your c# code can participate in the pipeline.

Upvotes: 5

Rik
Rik

Reputation: 29243

Yes. You can use .NET classes in powershell, for instance you can use:

PS C:\> [System.Environment]::GetLogicalDrives()

when dealing with a static method.

Upvotes: 1

Iain
Iain

Reputation: 6452

Powershell uses the .net Framework under the covers, all objects are CLR object

Upvotes: 0

Related Questions