1

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.

1 Answer 1

1

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.

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

1 Comment

Makes sense. Will try it in the AM. If I can come up with my old sample again, I will post it here but I still had the function declared after the $list loop.

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.