1

How can I pass a cmdlet as a parameter value in C#? In other words, what would the the .NET equivalent of the following be?

PS> Get-Content -Path (Some-Cmdlet)

I have the following code:

var ps = PowerShell.Create(session);
ps.AddComand("Get-Content").AddParameter("Path", "(Some-Cmdlet)");

However, the string "(Some-Cmdlet)" gets passed verbatim. It is not interpreted. I have also tried:

var ps = PowerShell.Create(session);
var cmd = new Command("Some-Cmdlet");
ps.AddComand("Get-Content").AddParameter("Path", cmd);

Unfortunately, it gives the same result. It seems to be calling ToString() on the Command object, rather than evaluating it.

Swoogan
  • 5,298
  • 5
  • 35
  • 47

1 Answers1

0

It appears that there is no way to have a parameter value evaluated. From what I can discover, you need to use AddScript instead of AddCommand. It's also necessary to alter the expression, from what you would write on the commandline, if you want to have parameters.

In my case, I used the form:

var flag = "xyz";
ps.AddScript(@"param([string]$Flag) Get-Content -Path (Some-Cmdlet -Flag $Flag)")
    .AddParameter("Flag", flag);

There may be a better way, but this works.

Swoogan
  • 5,298
  • 5
  • 35
  • 47