3

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

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the only answer that is related to "C# .exe" :) Voted up. The others are obviously missing that.
4

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.

Comments

1

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

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

when dealing with a static method.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.