I am having trouble trying to call a Powershell function with C #. In particular, I'm stuck trying to pass a generic Project list 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 common list of Project and Project is a custom class. My module function signature is as follows:
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 get this error when I try to iterate over an array:
{"Property" State "could not be found on this object. Make sure it exists." }
Can I do what I'm trying to do?
Edit: For some time I used the code below, but ended up using C # code for this web application. The loading time for creating a powershell session was too long 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); } }
source share