3

Is there a way to do this PowerShell statement in C#

$myvariable = New-PSSessionOption -SomeParameter -AnotherParameter -YetAnotherParameter

I know how to run commands and add parameters (PowerShell.AddCommand etc), but I'm missing something that lets me do an entire statement.

The docs do suggest there is an 'AddStatement' method on the PowerShell class, but it's not there in reality.

Or am I better just putting it all in a script and just calling that from my C# instead?

Thanks

2
  • I think it's twigged. Basically break it down into loads of little individual calls. The Invoke method returns a collection of PSObject, which will be the result of the command, and you can then feed them into the next command as parameters/arguments etc. Commented Nov 24, 2011 at 16:10
  • AddStatement is in PowerShell v3 (still in CTP) Commented Nov 24, 2011 at 18:28

1 Answer 1

2

The AddStatement is only in the PowerShell v3 CTP (which is not production ready yet)

It's actually simpler than you think. That line should be treated as a script. A script doesn't neccessarily mean a physical ps1 file. Use the AddScript method:

var ps = PowerShell.Create();
ps.Commands.AddScript("$myvariable = New-PSSessionOption ...");
ps.Invoke();
Sign up to request clarification or add additional context in comments.

1 Comment

Just to add a bit to this, I was also struggling with creating a powershell script (via C#) that created a PSCredential object. This takes a username and password as constructor args, which (at least I don't think) you can do using the AddScript method. You can build up a string, but the password is a SecureString object, which you can't build into a string - needs to be passed as the object itself. But, Just realised that the API has an object called PSCredential. You can just construct using the API in C# (new PSCredential("username", password) (password is the result of a previous PS call).

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.