I'm having trouble trying to call a Powershell function from C#. Specifically, I'm getting stuck trying to pass a generic list of Project's to a powershell module function. Here is the code:
var script = @". \\server01\Modules\Runspace.ps1; Get-MyCommand";
var allProjects = _pmRepository.GetAllProjects();
using (Runspace runSpace = RunspaceFactory.CreateRunspace())
{
runSpace.Open();
PowerShell posh = PowerShell.Create();
posh.Runspace = runSpace;
posh.AddScript(script);
posh.AddArgument(allProjects);
Collection<PSObject> results = posh.Invoke();
}
The GetAllProjects() method returns a generic list of Project's and Project is a custom class. My module function signature looks like this:
function Get-MyCommand
{
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline = $true)]
[PSCustomObject[]] $Projects
)
Begin
{}
Process
{
$consumables = New-GenericList "Company.Project.Entities.Project"
foreach($project in $projects)
{
if ($project.State -eq $ProjectStates.Development)
{
$consumables.Add($project)
}
}
}
}
I'm getting this error when I try to iterate over the array:
{"Property 'State' cannot be found on this object. Make sure that it exists."}
Is it possible to do what I'm trying to do?
Edit: I used the below code for a while, but ended up consuming the back-end C# code for this web application. The load time to create a powershell session was just too great for our situation. Hope this helps.
private void LoadConsumableProjects()
{
var results = new Collection<PSObject>();
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(_modules);
using (Runspace runSpace = RunspaceFactory.CreateRunspace(iss))
{
runSpace.Open();
using (var ps = PowerShell.Create())
{
ps.Runspace = runSpace;
ps.AddScript("Get-LatestConsumableProjects $args[0]");
ps.AddArgument(Repository.GetAllProjects().ToArray());
results = ps.Invoke();
if (ps.Streams.Error.Count > 0)
{
var errors = "Errors";
}
}
}
_projects = new List<Project>();
foreach (var psObj in results)
{
_projects.Add((Project)psObj.BaseObject);
}
}