Kenpachii
Kenpachii

Reputation: 145

Calling PowerShell function from within the script in C# Application

I just started playing with PowerShell two days ago. I am running a PowerShell script form a C# console application. I pass in a list of objects (MyObj1) as a parameter to the script and do some data manipulation to the object. However, when I call a function within the script I get a function not recognized error while printing out the errors. Here is a small sample of what I am doing.

public class MyObj1
{
    public string Property1 {get; set;}
    public int Property2 {get; set;}
}

Here is part of code that I am using to run the script:

var rs = RunspaceFactory.CreateRunspace();
rs.Open();
rs.SessionStateProxy.SetVariable("list", myObjectList);
rs.SessionStateProxy.SetVariable("xml", xml);
var ps = PowerShell.Create();
ps.Runspace = rs;
var psScript = System.IO.File.ReadAllText(@"C:\temp\ps.ps1");
ps.AddScript(psScript);
ps.Invoke();
foreach (var item in myObjectList)
{
    Console.WriteLine(item.Property1 + "; " + item.Property1);
}

Console.WriteLine("\n================================ ERRORS ============================ \n");

foreach (ErrorRecord err in ps.Streams.Error)
{
    Console.WriteLine(err.ToString());
}

And here is the actual script:

$list | ForEach {
    $_.Property1 = $_.GetType()
    DoSomeThing ([ref] $_)
}

Function DoSomeThing ($MyObject)
{
    $Asset.Property2 = $Asset.Property2 + $Asset.Property2
}

Two days ago while I was playing with same script using some dummy classes like above, I was able to modify the data but since this morning, I have modified the script to use real classes. And Ctrl+Z will only take me back to a certain point in my editor. In the ForEach loop everything works until I cal the function.

As for the project, the plan is to push this application with required data manipulation in C# and then have some optional changes done in the script. The point is to avoid push to the application to production server and handling all/most data manipulation in the script.

Upvotes: 1

Views: 707

Answers (1)

dmay
dmay

Reputation: 1325

Move function declaration to the beginnig of the script file.

Function DoSomeThing ($MyObject)
{
    $Asset.Property2 = $Asset.Property2 + $Asset.Property2
}

$list | ForEach {
    $_.Property1 = $_.GetType()
    DoSomeThing ([ref] $_)
}

PS doesn't compile script, it executes it command by command. So you have to create/declare function before you use it.

Upvotes: 1

Related Questions